Java Examples for javax.xml.ws.soap.SOAPFaultException

The following java examples will help you to understand the usage of javax.xml.ws.soap.SOAPFaultException. These source code samples are taken from different open source projects.

Example 1
Project: camelinaction2-master  File: WssAuthTest.java View source code
@Test
public void testBadUser() throws Exception {
    OrderEndpoint client = createCXFClient("http://localhost:9000/order", "rider", "camelinaction.wssecurity.ClientPasswordCallback");
    try {
        OrderResult reply = client.order(new Order("motor", 100, "honda"));
        Assert.fail();
    } catch (javax.xml.ws.soap.SOAPFaultException e) {
    }
}
Example 2
Project: cxf-master  File: AbstractTypeTestClient.java View source code
@Test
public void testStringList() throws Exception {
    if (!shouldRunTest("StringList")) {
        return;
    }
    if (testDocLiteral || testXMLBinding) {
        List<String> x = Arrays.asList("I", "am", "SimpleList");
        List<String> yOrig = Arrays.asList("Does", "SimpleList", "Work");
        Holder<List<String>> y = new Holder<List<String>>(yOrig);
        Holder<List<String>> z = new Holder<List<String>>();
        List<String> ret = testDocLiteral ? docClient.testStringList(x, y, z) : xmlClient.testStringList(x, y, z);
        if (!perfTestOnly) {
            assertTrue("testStringList(): Incorrect value for inout param", x.equals(y.value));
            assertTrue("testStringList(): Incorrect value for out param", yOrig.equals(z.value));
            assertTrue("testStringList(): Incorrect return value", x.equals(ret));
        }
        if (testDocLiteral) {
            try {
                ret = docClient.testStringList(null, y, z);
            } catch (SOAPFaultException ex) {
                assertTrue(ex.getMessage(), ex.getMessage().contains("Unmarshalling"));
            }
        }
    } else {
        String[] x = { "I", "am", "SimpleList" };
        String[] yOrig = { "Does", "SimpleList", "Work" };
        Holder<String[]> y = new Holder<String[]>(yOrig);
        Holder<String[]> z = new Holder<String[]>();
        String[] ret = rpcClient.testStringList(x, y, z);
        assertTrue(y.value.length == 3);
        assertTrue(z.value.length == 3);
        assertTrue(ret.length == 3);
        if (!perfTestOnly) {
            for (int i = 0; i < 3; i++) {
                assertEquals("testStringList(): Incorrect value for inout param", x[i], y.value[i]);
                assertEquals("testStringList(): Incorrect value for out param", yOrig[i], z.value[i]);
                assertEquals("testStringList(): Incorrect return value", x[i], ret[i]);
            }
        }
    }
}
Example 3
Project: elpaaso-core-master  File: ApplicationStoriesSteps.java View source code
@When("^(.+) creates an application with code (.+) and label (.+)$")
public void whenPaasUserCreatesAnApplicationWithLabelAndcode(String paasUser, String code, String label) {
    try {
        CreateApplicationCommand command = new CreateApplicationCommand();
        command.setCode(code);
        command.setLabel(label);
        command.setIsPublic(true);
        applicationUID = paasAdministrationServiceProxy.createApplication(command, credentials.get(paasUser));
    } catch (DuplicateApplicationErrorFault e) {
        throwable = e;
    } catch (javax.xml.ws.soap.SOAPFaultException ex) {
        throwable = ex;
    } catch (PaasUserNotFoundErrorFault e) {
        throwable = e;
    } catch (Exception e) {
        throwable = e;
    }
}
Example 4
Project: BansheeCore-master  File: SOAPUtils.java View source code
public static String getFaultData(SOAPFaultException responseException, SOAPVersion version) throws Exception {
    ByteArrayOutputStream baos = null;
    try {
        Node n = responseException.getFault().getDetail().getFirstChild();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        DOMSource domSource = new DOMSource(n);
        StringWriter stringWriter = new StringWriter();
        StreamResult result = new StreamResult(stringWriter);
        transformer.transform(domSource, result);
        return stringWriter.getBuffer().toString();
    } catch (Exception ex) {
        throw ex;
    } finally {
        if (baos != null) {
            baos.close();
        }
    }
}
Example 5
Project: glassfish-master  File: SOAPWebConsumer.java View source code
private void addUsingSOAPConsumer() {
    com.example.calculator.Calculator port = null;
    port = service.getCalculatorPort();
    // Get Stub
    BindingProvider stub = (BindingProvider) port;
    String endpointURI = "http://localhost:12011/calculatorendpoint";
    stub.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURI);
    String failedMsg = null;
    try {
        System.out.println("\nInvoking throwRuntimeException");
        port.throwRuntimeException("bhavani");
    } catch (Exception ex) {
        System.out.println(ex);
        if (!(ex instanceof SOAPFaultException) || !(ex.getMessage().equals("java.lang.RuntimeException: Calculator :: Threw Runtime Exception"))) {
            failedMsg = "port.throwRuntimeException() did not receive RuntimeException 'Calculator :: Threw Runtime Exception'";
        }
    }
    try {
        System.out.println("\nInvoking throwApplicationException");
        port.throwApplicationException("bhavani");
    } catch (Exception ex) {
        System.out.println(ex);
        if (!(ex instanceof com.example.calculator.Exception_Exception)) {
            failedMsg = "port.throwApplicationException() did not throw ApplicationException";
        }
    }
    if (failedMsg != null) {
        stat.addStatus(testId, stat.FAIL);
    } else {
        stat.addStatus(testId, stat.PASS);
    }
}
Example 6
Project: tesb-rt-se-master  File: TestProviderJob.java View source code
@javax.jws.WebMethod(operationName = "invoke", action = "http://talend.org/esb/service/job/invoke")
@javax.jws.WebResult(name = "jobOutput", targetNamespace = "http://talend.org/esb/service/job", // targetNamespace = "",
partName = "response")
public javax.xml.transform.Source invoke(@javax.jws.WebParam(name = "jobInput", targetNamespace = "http://talend.org/esb/service/job", // targetNamespace = "",
partName = "request") javax.xml.transform.Source request) {
    try {
        org.dom4j.io.DocumentResult docResult = new org.dom4j.io.DocumentResult();
        factory.newTransformer().transform(request, docResult);
        org.dom4j.Document requestDoc = docResult.getDocument();
        // System.out.println("request: " +
        // requestDoc.asXML());
        QueuedExchangeContextImpl<org.dom4j.Document> messageExchange = messageHandler.invoke(requestDoc);
        try {
            if (messageExchange.isFault()) {
                String faultString = messageExchange.getFaultMessage();
                if (messageExchange.isBusinessFault()) {
                    org.dom4j.Document faultDoc = messageExchange.getBusinessFaultDetails();
                    javax.xml.soap.SOAPFactory soapFactory = javax.xml.soap.SOAPFactory.newInstance();
                    javax.xml.soap.SOAPFault soapFault = soapFactory.createFault(faultString, new javax.xml.namespace.QName(TNS, "businessFault"));
                    if (null != faultDoc) {
                        // System.out.println("business fault details: "
                        // + faultDoc.asXML());
                        org.dom4j.io.DOMWriter writer = new org.dom4j.io.DOMWriter();
                        org.w3c.dom.Document faultDetailDom = writer.write(faultDoc);
                        soapFault.addDetail().appendChild(soapFault.getOwnerDocument().importNode(faultDetailDom.getDocumentElement(), true));
                    }
                    throw new javax.xml.ws.soap.SOAPFaultException(soapFault);
                } else {
                    Throwable error = messageExchange.getFault();
                    // error.getMessage());
                    if (error instanceof RuntimeException) {
                        throw (RuntimeException) error;
                    } else {
                        throw new RuntimeException(faultString, error);
                    }
                }
            } else {
                org.dom4j.Document responseDoc = messageExchange.getResponse();
                if (null == responseDoc) {
                    // System.out.println("response: empty");
                    throw new RuntimeException("no response provided by Talend job");
                }
                return new org.dom4j.io.DocumentSource(responseDoc);
            }
        } finally {
            messageExchange.completeQueuedProcessing();
        }
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Throwable ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
    // System.out.println(System.currentTimeMillis() +
    // " <- handleMessage");
    }
}
Example 7
Project: fcrepo-master  File: TestXACMLPolicies.java View source code
public void invokeAPIMFailure(FedoraClient user, String username, String functionToTest, Class<?> args[], Object parms[]) {
    // APIA access by user without access- should fail
    try {
        System.out.println("Testing " + functionToTest + " from invalid user: " + username);
        FedoraAPIMMTOM apim1 = user.getAPIMMTOM();
        Method func = apim1.getClass().getMethod(functionToTest, args);
        func.invoke(apim1, parms);
        fail("Illegal access allowed");
    } catch (InvocationTargetException ite) {
        Throwable cause = ite.getCause();
        if (cause instanceof SOAPFaultException) {
            SOAPFaultException af = (SOAPFaultException) cause;
            System.out.println("    Reason = " + af.getMessage());
            assertTrue(af.getMessage(), af.getMessage().contains("Authorization Denied"));
            System.out.println("Access denied correctly");
        } else {
            System.out.println("Got exception: " + cause.getClass().getName());
            fail("Illegal access dis-allowed for some other reason: " + cause.getClass().getName());
        }
    } catch (IOException ioe) {
        System.out.println("    Reason = " + ioe.getMessage());
        assertTrue(ioe.getMessage().contains("[403 Forbidden]"));
        System.out.println("Access denied correctly");
    } catch (Exception ae) {
        String message = "Some other exception: " + ae.toString();
        System.out.println(message);
        fail(message);
    }
}
Example 8
Project: anythingworks-master  File: SoapFaultExceptionTranslator.java View source code
@NotNull
@Override
public Exception translate(@NotNull Throwable t) throws Exception {
    SOAPFaultException e = (SOAPFaultException) t;
    ServiceException exToThrow = null;
    try {
        SOAPFault fault = e.getFault();
        if (fault != null) {
            Detail detail = fault.getDetail();
            if (detail != null) {
                SoapFaultInfo faultInfo = extractFaultInfo(detail);
                exToThrow = converter.makeException(faultInfo);
            }
        }
    } catch (RuntimeException exWhileTryingToMakeEx) {
        log.error("Failed translating exception: " + exWhileTryingToMakeEx.getMessage(), exWhileTryingToMakeEx);
        throw e;
    }
    if (exToThrow != null) {
        //good.
        throw exToThrow;
    } else {
        //arriving here means we could not translate it. this should not happen.
        //let's keep what we had and rethrow.
        log.error("Failed translating exception!");
        throw e;
    }
}
Example 9
Project: axis2-java-master  File: AddNumbersHandlerTests.java View source code
/**
     * Client app sends MAXVALUE, MAXVALUE as params to add.
     * No client-side handlers are configured for this scenario.  
     * The endpoint method (addNumbersHandler) will detect the possible overflow and
     * throw an unchecked exception, NullPointerException.
     * 
     * The server-side AddNumbersProtocolHandler will
     * access the thrown exception using the "jaxws.webmethod.exception"
     * property and add the stack trace string to fault string.
     * 
     * The client should receive a SOAPFaultException that has a stack
     * trace as part of the message.
     * This test verifies the following:
     * 
     * 1)  Proper exception/fault processing when handlers are installed.
     * 2)  Access to the special "jaxws.webmethod.exception"
     * 3)  Proper exception call flow when an unchecked exception is thrown.
     */
public void testAddNumbersHandler_WithUnCheckedException() throws Exception {
    TestLogger.logger.debug("----------------------------------");
    TestLogger.logger.debug("test: " + getName());
    AddNumbersHandlerService service = new AddNumbersHandlerService();
    AddNumbersHandlerPortType proxy = service.getAddNumbersHandlerPort();
    BindingProvider p = (BindingProvider) proxy;
    p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, axisEndpoint);
    SOAPFaultException expectedException = null;
    Throwable t = null;
    try {
        proxy.addNumbersHandler(-1000, Integer.MIN_VALUE);
    } catch (Throwable e) {
        t = e;
    }
    // Make sure the proper exception is thrown
    if (t == null) {
        fail("Expected AddNumbersHandlerFault_Exception to be thrown");
    }
    if (t instanceof SOAPFaultException) {
        expectedException = (SOAPFaultException) t;
    } else {
        fail("Expected SOAPFaultException to be thrown, " + "but the exception is: " + t);
    }
    // also confirm that @PreDestroy method is called.  Since it only makes sense to call it on the managed
    // (server) side and just before the handler instance goes out of scope, we are creating a file in the
    // @PreDestroy method, and will check for its existance here.  If the file does not exist, it means
    // @PreDestroy method was never called.  The file is set to .deleteOnExit(), so no need to delete it.
    File file = new File("AddNumbersProtocolHandler.preDestroy.txt");
    assertTrue("File AddNumbersProtocolHandler.preDestroy.txt does not exist, meaning the @PreDestroy method was not called.", file.exists());
    String log = readLogFile();
    String expected_calls = "AddNumbersLogicalHandler2 POST_CONSTRUCT\n" + "AddNumbersProtocolHandler2 GET_HEADERS\n" + "AddNumbersProtocolHandler GET_HEADERS\n" + "AddNumbersProtocolHandler HANDLE_MESSAGE_INBOUND\n" + "AddNumbersProtocolHandler2 HANDLE_MESSAGE_INBOUND\n" + "AddNumbersLogicalHandler2 HANDLE_MESSAGE_INBOUND\n" + "AddNumbersLogicalHandler HANDLE_MESSAGE_INBOUND\n" + "AddNumbersLogicalHandler HANDLE_FAULT_OUTBOUND\n" + "AddNumbersLogicalHandler2 HANDLE_FAULT_OUTBOUND\n" + "AddNumbersProtocolHandler2 HANDLE_FAULT_OUTBOUND\n" + "AddNumbersProtocolHandler HANDLE_FAULT_OUTBOUND\n" + "AddNumbersLogicalHandler CLOSE\n" + "AddNumbersLogicalHandler2 CLOSE\n" + "AddNumbersProtocolHandler2 CLOSE\n" + "AddNumbersProtocolHandler CLOSE\n" + "AddNumbersProtocolHandler PRE_DESTROY\n";
    assertTrue("Expected : " + expected_calls + " but received " + log, expected_calls.equals(log));
    // The outbound service handler adds the stack trace to the 
    // message.  Make sure the stack trace contains the AddNumbersHandlerPortTypeImpl
    TestLogger.logger.debug("Expected Exception is " + expectedException.getMessage());
    SOAPFault fault = expectedException.getFault();
    assertTrue("A stack trace was not present in the returned exception's message:" + fault.getFaultString(), fault.getFaultString().indexOf("AddNumbersHandlerPortTypeImpl") > 0);
    TestLogger.logger.debug("----------------------------------");
}
Example 10
Project: JBossAS51-master  File: WebMethodTestCase.java View source code
public void testIllegalDispatchAccess() throws Exception {
    URL wsdlURL = new URL(endpointURL + "?wsdl");
    QName serviceName = new QName(targetNS, "EndpointService");
    QName portName = new QName(targetNS, "EndpointPort");
    String reqPayload = "<ns1:noWebMethod xmlns:ns1='" + targetNS + "'>" + " <String_1>Hello</String_1>" + "</ns1:noWebMethod>";
    String expPayload = "<env:Fault xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>" + " <faultcode>env:Client</faultcode>" + " <faultstring>Endpoint {http://webmethod.samples.jaxws.ws.test.jboss.org/}EndpointPort does not contain operation meta data for: {http://webmethod.samples.jaxws.ws.test.jboss.org/}noWebMethod</faultstring>" + "</env:Fault>";
    Service service = Service.create(wsdlURL, serviceName);
    Dispatch dispatch = service.createDispatch(portName, Source.class, Mode.PAYLOAD);
    try {
        dispatch.invoke(new StreamSource(new StringReader(reqPayload)));
        fail("SOAPFaultException expected");
    } catch (SOAPFaultException ex) {
    }
}
Example 11
Project: JBossAS_5_1_EDG-master  File: WebMethodTestCase.java View source code
public void testIllegalDispatchAccess() throws Exception {
    URL wsdlURL = new URL(endpointURL + "?wsdl");
    QName serviceName = new QName(targetNS, "EndpointService");
    QName portName = new QName(targetNS, "EndpointPort");
    String reqPayload = "<ns1:noWebMethod xmlns:ns1='" + targetNS + "'>" + " <String_1>Hello</String_1>" + "</ns1:noWebMethod>";
    String expPayload = "<env:Fault xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>" + " <faultcode>env:Client</faultcode>" + " <faultstring>Endpoint {http://webmethod.samples.jaxws.ws.test.jboss.org/}EndpointPort does not contain operation meta data for: {http://webmethod.samples.jaxws.ws.test.jboss.org/}noWebMethod</faultstring>" + "</env:Fault>";
    Service service = Service.create(wsdlURL, serviceName);
    Dispatch dispatch = service.createDispatch(portName, Source.class, Mode.PAYLOAD);
    try {
        dispatch.invoke(new StreamSource(new StringReader(reqPayload)));
        fail("SOAPFaultException expected");
    } catch (SOAPFaultException ex) {
    }
}
Example 12
Project: jbossws-cxf-master  File: WebMethodTestCase.java View source code
@Test
@RunAsClient
public void testIllegalDispatchAccess() throws Exception {
    URL wsdlURL = new URL(baseURL + "/TestService?wsdl");
    QName serviceName = new QName(targetNS, "EndpointService");
    QName portName = new QName(targetNS, "EndpointPort");
    String reqPayload = "<ns1:noWebMethod xmlns:ns1='" + targetNS + "'>" + " <String_1>Hello</String_1>" + "</ns1:noWebMethod>";
    Service service = Service.create(wsdlURL, serviceName);
    Dispatch<Source> dispatch = service.createDispatch(portName, Source.class, Mode.PAYLOAD);
    try {
        dispatch.invoke(new StreamSource(new StringReader(reqPayload)));
        fail("SOAPFaultException expected");
    } catch (SOAPFaultException ex) {
    }
}
Example 13
Project: spring-ws-samples-master  File: Main.java View source code
public static void main(String[] args) throws MalformedURLException, DatatypeConfigurationException {
    try {
        AirlineService service;
        if (args.length == 0) {
            service = new AirlineService();
        } else {
            QName serviceName = new QName("http://www.springframework.org/spring-ws/samples/airline/definitions", "AirlineService");
            service = new AirlineService(new URL(args[0]), serviceName);
        }
        Airline airline = service.getAirlineSoap11();
        GetFlightsRequest request = new GetFlightsRequest();
        request.setFrom("AMS");
        request.setTo("VCE");
        XMLGregorianCalendar departureDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(2006, 1, 31, DatatypeConstants.FIELD_UNDEFINED);
        request.setDepartureDate(departureDate);
        System.out.format("Requesting flights on %1tD%n", departureDate.toGregorianCalendar());
        GetFlightsResponse response = airline.getFlights(request);
        System.out.format("Got %1d results%n", response.getFlight().size());
        if (!response.getFlight().isEmpty()) // Book the first flight using John Doe as a frequent flyer
        {
            Flight flight = response.getFlight().get(0);
            BookFlightRequest bookFlightRequest = new BookFlightRequest();
            bookFlightRequest.setFlightNumber(flight.getNumber());
            bookFlightRequest.setDepartureTime(flight.getDepartureTime());
            BookFlightRequest.Passengers passengers = new BookFlightRequest.Passengers();
            passengers.getPassengerOrUsername().add("john");
            bookFlightRequest.setPassengers(passengers);
            Ticket ticket = airline.bookFlight(bookFlightRequest);
            writeTicket(ticket);
        }
    } catch (SOAPFaultException ex) {
        System.out.format("SOAP Fault Code    %1s%n", ex.getFault().getFaultCodeAsQName());
        System.out.format("SOAP Fault String: %1s%n", ex.getFault().getFaultString());
    }
}
Example 14
Project: betsy-master  File: TestPartnerPortTypeRegular.java View source code
public int startProcessSync(final int inputPart) throws FaultMessage {
    String logHeader = "Partner: startProcessSync with input " + inputPart;
    logInfo(logHeader);
    if (inputPart == CODE_THROW_CUSTOM_FAULT) {
        logInfo(logHeader + " - Throwing CustomFault");
        SOAPFault sf = createSoapFault();
        throw new SOAPFaultException(sf);
    } else if (inputPart == CODE_THROW_FAULT) {
        logInfo(logHeader + " - Throwing Fault");
        throw new FaultMessage("expected Error", inputPart);
    } else {
        final int result = detectConcurrency(inputPart);
        logInfo(logHeader + " - Returning " + result);
        return result;
    }
}
Example 15
Project: Consent2Share-master  File: SamlTokenParser.java View source code
/*
	 * Convenience function used to generate a generic SOAPFaultException
	 */
private SOAPFaultException createSOAPFaultException(String faultString, Boolean clientFault) {
    try {
        String faultCode = clientFault ? "Client" : "Server";
        SOAPFault fault = SOAPFactory.newInstance().createFault();
        fault.setFaultString(faultString);
        fault.setFaultCode(new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE, faultCode));
        return new SOAPFaultException(fault);
    } catch (SOAPException e) {
        throw new RuntimeException("Error creating SOAP Fault message, faultString: " + faultString);
    }
}
Example 16
Project: jaxws-master  File: EndToEndErrorTester.java View source code
/*
     * Have one of the client handlers throw a protocol exception
     * and check that the proper methods are called. This test
     * is on outbound message with 2.0 handler (so handleFault
     * should not be called on the handler that throws the
     * exception). Testing with soap handler.
     *
     * Exception should result in a fault in the message, which
     * is dispatched to and wrapped by the client.
     *
     * This test checks the fault code as well -- test for
     * bug 6350633.
     */
public void testClientOutboundProtocolException1() throws Exception {
    // the expected fault code local part
    String client = "Client";
    TestService_Service service = getService();
    TestService testStub = getTestStub(service);
    ReportService reportStub = getReportStub(service);
    HandlerTracker tracker = HandlerTracker.getClientInstance();
    reportStub.clearHandlerTracker();
    tracker.clearAll();
    for (int i = 0; i < numTotalHandlers; i++) {
        tracker.setHandlerAction(CLIENT_PREFIX + i, HA_REGISTER_HANDLE_XYZ);
    }
    tracker.setHandlerAction(CLIENT_PREFIX + 5, HA_THROW_PROTOCOL_EXCEPTION_OUTBOUND);
    try {
        testStub.testInt(42);
        fail("did not receive an exception");
    } catch (SOAPFaultException e) {
        SOAPFault fault = e.getFault();
        String faultCode = fault.getFaultCode();
        assertTrue("fault code should end with \"" + client + "\": " + faultCode, faultCode.endsWith(client));
    }
    // check result
    String[] called = { "0", "1", "3", "4", "5", "4_FAULT", "3_FAULT", "1_FAULT", "0_FAULT" };
    int[] closed = { 5, 4, 3, 1, 0 };
    List<String> calledHandlers = tracker.getCalledHandlers();
    assertEquals("Did not get proper number of called handlers", called.length, calledHandlers.size());
    for (int i = 0; i < called.length; i++) {
        assertEquals("did not find expected handler", CLIENT_PREFIX + called[i], calledHandlers.get(i));
    }
    List<String> closedHandlers = tracker.getClosedHandlers();
    assertEquals("Did not get proper number of closed handlers", closed.length, closedHandlers.size());
    for (int i = 0; i < closed.length; i++) {
        assertEquals("did not find expected handler", CLIENT_PREFIX + closed[i], closedHandlers.get(i));
    }
    // should be no destroyed handlers
    List<String> destroyedHandlers = tracker.getDestroyedHandlers();
    assertTrue("Should be 0 destroyed handlers", destroyedHandlers.isEmpty());
}
Example 17
Project: juddi-master  File: UDDI_140_NegativePublicationIntegrationTest.java View source code
//<editor-fold defaultstate="collapsed" desc="Business Name tests">
@Test(expected = SOAPFaultException.class)
public void BusinessKeyTooLongTest() throws DispositionReportFaultMessage, RemoteException {
    Assume.assumeTrue(TckPublisher.isEnabled());
    System.out.println("BusinessKeyTooLongTest");
    SaveBusiness sb = new SaveBusiness();
    sb.setAuthInfo(authInfoJoe);
    BusinessEntity be = new BusinessEntity();
    Name n = new Name();
    n.setValue("BusinessKeyTooLongTest -Hello Nurse");
    be.getName().add(n);
    be.setBusinessKey(strkey256_1);
    sb.getBusinessEntity().add(be);
    try {
        BusinessDetail saveBusiness = publicationJoe.saveBusiness(sb);
        DeleteBusiness db = new DeleteBusiness();
        db.setAuthInfo(authInfoJoe);
        db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey());
        publicationJoe.deleteBusiness(db);
        Assert.fail("request should have been rejected");
    } catch (SOAPFaultException ex) {
        HandleException(ex);
        throw ex;
    }
}
Example 18
Project: mysaml-master  File: SamlAuthenticationHandler.java View source code
private void createAndThrowSOAPFault(SOAPMessage message, String faultString) throws SOAPException {
    SOAPHeader header = message.getSOAPHeader();
    header.removeContents();
    SOAPBody body = message.getSOAPPart().getEnvelope().getBody();
    body.removeContents();
    SOAPFault fault = body.addFault();
    fault.setFaultString(faultString);
    throw new SOAPFaultException(fault);
}
Example 19
Project: narayana-master  File: TerminationCoordinatorRPCProcessorImpl.java View source code
/**
     * Cancel.
     * @param cancel The cancel notification.
     * @param map The addressing context.
     * @param arjunaContext The arjuna context.
     */
public void cancel(final NotificationType cancel, final MAP map, final ArjunaContext arjunaContext) {
    final InstanceIdentifier instanceIdentifier = arjunaContext.getInstanceIdentifier();
    final BusinessActivityTerminator participant = TerminationCoordinatorProcessor.getProcessor().getParticipant(instanceIdentifier);
    try {
        if (participant != null) {
            try {
                participant.cancel();
            } catch (FaultedException fm) {
                SOAPFactory factory = SOAPFactory.newInstance();
                SOAPFault soapFault = factory.createFault(SoapFaultType.FAULT_RECEIVER.getValue(), ArjunaTXConstants.FAULTED_ERROR_CODE_QNAME);
                throw new SOAPFaultException(soapFault);
            } catch (final UnknownTransactionException ute) {
                SOAPFactory factory = SOAPFactory.newInstance();
                SOAPFault soapFault = factory.createFault(SoapFaultType.FAULT_SENDER.getValue(), ArjunaTXConstants.UNKNOWNTRANSACTION_ERROR_CODE_QNAME);
                soapFault.addDetail().addDetailEntry(ArjunaTXConstants.UNKNOWNTRANSACTION_ERROR_CODE_QNAME).addTextNode(WSTLogger.i18NLogger.get_wst11_messaging_TerminationCoordinatorProcessorImpl_1());
                throw new SOAPFaultException(soapFault);
            } catch (final SystemException se) {
                SOAPFactory factory = SOAPFactory.newInstance();
                SOAPFault soapFault = factory.createFault(SoapFaultType.FAULT_RECEIVER.getValue(), ArjunaTXConstants.UNKNOWNERROR_ERROR_CODE_QNAME);
                soapFault.addDetail().addDetailEntry(ArjunaTXConstants.UNKNOWNERROR_ERROR_CODE_QNAME).addTextNode(WSTLogger.i18NLogger.get_wst11_messaging_TerminationCoordinatorProcessorImpl_2());
                throw new SOAPFaultException(soapFault);
            } catch (final Throwable th) {
                if (WSTLogger.logger.isTraceEnabled()) {
                    WSTLogger.logger.tracev("Unexpected exception thrown from close:", th);
                }
                SOAPFactory factory = SOAPFactory.newInstance();
                SOAPFault soapFault = factory.createFault(SoapFaultType.FAULT_RECEIVER.getValue(), ArjunaTXConstants.UNKNOWNERROR_ERROR_CODE_QNAME);
                soapFault.addDetail().addDetailEntry(ArjunaTXConstants.UNKNOWNERROR_ERROR_CODE_QNAME).addTextNode(WSTLogger.i18NLogger.get_wst11_messaging_TerminationCoordinatorProcessorImpl_2());
                throw new SOAPFaultException(soapFault);
            }
        } else {
            if (WSTLogger.logger.isTraceEnabled()) {
                WSTLogger.logger.tracev("Cancel called on unknown participant: {0}", new Object[] { instanceIdentifier });
            }
            SOAPFactory factory = SOAPFactory.newInstance();
            SOAPFault soapFault = factory.createFault(SoapFaultType.FAULT_SENDER.getValue(), ArjunaTXConstants.UNKNOWNTRANSACTION_ERROR_CODE_QNAME);
            soapFault.addDetail().addDetailEntry(ArjunaTXConstants.UNKNOWNTRANSACTION_ERROR_CODE_QNAME).addTextNode(WSTLogger.i18NLogger.get_wst11_messaging_TerminationCoordinatorProcessorImpl_5());
            throw new SOAPFaultException(soapFault);
        }
    } catch (SOAPException se) {
        se.printStackTrace(System.err);
        throw new ProtocolException(se);
    }
}
Example 20
Project: quickstarts-master  File: ReverseService.java View source code
@POST
@Path("/")
@WebMethod(action = "urn:switchyard-quickstart:camel-soap-proxy:1.0")
@WebResult(name = "text")
public String reverse(@WebParam(name = "text") String text) throws Exception {
    if (text.equals("fault")) {
        SOAPFactory factory = SOAPFactory.newInstance();
        SOAPFault sf = factory.createFault("myfaultstring", new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE, "Server"));
        sf.setFaultActor("myFaultActor");
        Detail d = sf.addDetail();
        QName entryName = new QName("urn:switchyard-quickstart:camel-soap-proxy:1.0", "order", "PO");
        DetailEntry entry = d.addDetailEntry(entryName);
        QName name = new QName("urn:switchyard-quickstart:camel-soap-proxy:1.0", "symbol");
        SOAPElement symbol = entry.addChildElement(name);
        symbol.addTextNode("SUNW");
        throw new SOAPFaultException(sf);
    }
    return new StringBuilder(text).reverse().toString();
}
Example 21
Project: tomee-master  File: MaxChildTest.java View source code
@Test
public void tooBig() throws MalformedURLException {
    try {
        final Root root = new Root();
        for (int i = 0; i < 2; i++) {
            root.getChildren().add(new Child());
        }
        javax.xml.ws.Service.create(new URL(this.root.toExternalForm() + "app/ws?wsdl"), new QName("http://cxf.server.openejb.apache.org/", "SimpleContractImplService")).getPort(SimpleContract.class).test(root);
    } catch (final SOAPFaultException e) {
        assertEquals("Unmarshalling Error: Maximum Number of Child Elements limit (1) Exceeded ", e.getMessage());
    }
}
Example 22
Project: wildfly-master  File: AbstractInvocationHandler.java View source code
protected void handleInvocationException(final Throwable t) throws Exception {
    if (t instanceof MBeanException) {
        throw ((MBeanException) t).getTargetException();
    }
    if (t instanceof Exception) {
        if (t instanceof InvocationTargetException) {
            throw (Exception) t;
        } else {
            SOAPFaultException ex = findSoapFaultException(t);
            if (ex != null) {
                throw new InvocationTargetException(ex);
            }
            throw new InvocationTargetException(t);
        }
    }
    if (t instanceof Error) {
        throw (Error) t;
    }
    throw new UndeclaredThrowableException(t);
}
Example 23
Project: camel-master  File: Soap11DataFormatAdapter.java View source code
/**
     * Creates an exception and eventually an embedded bean that contains the
     * fault detail. The exception class is determined by using the
     * elementNameStrategy. The qName of the fault detail should match the
     * WebFault annotation of the Exception class. If no fault detail is set a
     * SOAPFaultException is created.
     * 
     * @param fault Soap fault
     * @return created Exception
     */
private Exception createExceptionFromFault(Fault fault) {
    String message = fault.getFaultstring();
    Detail faultDetail = fault.getDetail();
    if (faultDetail == null || faultDetail.getAny().size() == 0) {
        try {
            return new SOAPFaultException(SOAPFactory.newInstance().createFault(message, fault.getFaultcode()));
        } catch (SOAPException e) {
            throw new RuntimeCamelException(e);
        }
    }
    Object detailObj = faultDetail.getAny().get(0);
    if (!(detailObj instanceof JAXBElement)) {
        try {
            return new SOAPFaultException(SOAPFactory.newInstance().createFault(message, fault.getFaultcode()));
        } catch (SOAPException e) {
            throw new RuntimeCamelException(e);
        }
    }
    JAXBElement<?> detailEl = (JAXBElement<?>) detailObj;
    Class<? extends Exception> exceptionClass = getDataFormat().getElementNameStrategy().findExceptionForFaultName(detailEl.getName());
    Constructor<? extends Exception> messageConstructor;
    Constructor<? extends Exception> constructor;
    try {
        Object detail = JAXBIntrospector.getValue(detailEl);
        try {
            constructor = exceptionClass.getConstructor(String.class, detail.getClass());
            return constructor.newInstance(message, detail);
        } catch (NoSuchMethodException e) {
            messageConstructor = exceptionClass.getConstructor(String.class);
            return messageConstructor.newInstance(message);
        }
    } catch (Exception e) {
        throw new RuntimeCamelException(e);
    }
}
Example 24
Project: cats-master  File: DeviceSearchServiceEndpointIT.java View source code
@Test(expected = SOAPFaultException.class)
public void findAllAllocatedSettopReservationDescTest() {
    List<SettopReservationDesc> settops;
    settops = deviceSearchService.findAllAllocatedSettopReservationDesc();
    for (SettopReservationDesc reservationDesc : settops) {
        Assert.assertTrue(reservationDesc instanceof SettopReservationDesc);
    }
    Assert.assertNotNull(settops);
    LOGGER.info(settops.size() + " settops  are allocated.");
}
Example 25
Project: classlib6-master  File: SOAPFaultBuilder.java View source code
private static Message createSOAP11Fault(SOAPVersion soapVersion, Throwable e, Object detail, CheckedExceptionImpl ce, QName faultCode) {
    SOAPFaultException soapFaultException = null;
    String faultString = null;
    String faultActor = null;
    Throwable cause = e.getCause();
    if (e instanceof SOAPFaultException) {
        soapFaultException = (SOAPFaultException) e;
    } else if (cause != null && cause instanceof SOAPFaultException) {
        soapFaultException = (SOAPFaultException) e.getCause();
    }
    if (soapFaultException != null) {
        QName soapFaultCode = soapFaultException.getFault().getFaultCodeAsQName();
        if (soapFaultCode != null)
            faultCode = soapFaultCode;
        faultString = soapFaultException.getFault().getFaultString();
        faultActor = soapFaultException.getFault().getFaultActor();
    }
    if (faultCode == null) {
        faultCode = getDefaultFaultCode(soapVersion);
    }
    if (faultString == null) {
        faultString = e.getMessage();
        if (faultString == null) {
            faultString = e.toString();
        }
    }
    Element detailNode = null;
    QName firstEntry = null;
    if (detail == null && soapFaultException != null) {
        detailNode = soapFaultException.getFault().getDetail();
        firstEntry = getFirstDetailEntryName((Detail) detailNode);
    } else if (ce != null) {
        try {
            DOMResult dr = new DOMResult();
            ce.getBridge().marshal(detail, dr);
            detailNode = (Element) dr.getNode().getFirstChild();
            firstEntry = getFirstDetailEntryName(detailNode);
        } catch (JAXBException e1) {
            faultString = e.getMessage();
            faultCode = getDefaultFaultCode(soapVersion);
        }
    }
    SOAP11Fault soap11Fault = new SOAP11Fault(faultCode, faultString, faultActor, detailNode);
    soap11Fault.captureStackTrace(e);
    Message msg = JAXBMessage.create(JAXB_CONTEXT, soap11Fault, soapVersion);
    return new FaultMessage(msg, firstEntry);
}
Example 26
Project: glassfish-main-master  File: SOAPWebConsumer.java View source code
private void addUsingSOAPConsumer() {
    com.example.calculator.Calculator port = null;
    port = service.getCalculatorPort();
    // Get Stub
    BindingProvider stub = (BindingProvider) port;
    String endpointURI = "http://localhost:12011/calculatorendpoint";
    stub.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURI);
    String failedMsg = null;
    try {
        System.out.println("\nInvoking throwRuntimeException");
        port.throwRuntimeException("bhavani");
    } catch (Exception ex) {
        System.out.println(ex);
        if (!(ex instanceof SOAPFaultException) || !(ex.getMessage().equals("java.lang.RuntimeException: Calculator :: Threw Runtime Exception"))) {
            failedMsg = "port.throwRuntimeException() did not receive RuntimeException 'Calculator :: Threw Runtime Exception'";
        }
    }
    try {
        System.out.println("\nInvoking throwApplicationException");
        port.throwApplicationException("bhavani");
    } catch (Exception ex) {
        System.out.println(ex);
        if (!(ex instanceof com.example.calculator.Exception_Exception)) {
            failedMsg = "port.throwApplicationException() did not throw ApplicationException";
        }
    }
    if (failedMsg != null) {
        stat.addStatus(testId, stat.FAIL);
    } else {
        stat.addStatus(testId, stat.PASS);
    }
}
Example 27
Project: ikvm-openjdk-master  File: SOAPFaultBuilder.java View source code
private static Message createSOAP11Fault(SOAPVersion soapVersion, Throwable e, Object detail, CheckedExceptionImpl ce, QName faultCode) {
    SOAPFaultException soapFaultException = null;
    String faultString = null;
    String faultActor = null;
    Throwable cause = e.getCause();
    if (e instanceof SOAPFaultException) {
        soapFaultException = (SOAPFaultException) e;
    } else if (cause != null && cause instanceof SOAPFaultException) {
        soapFaultException = (SOAPFaultException) e.getCause();
    }
    if (soapFaultException != null) {
        QName soapFaultCode = soapFaultException.getFault().getFaultCodeAsQName();
        if (soapFaultCode != null)
            faultCode = soapFaultCode;
        faultString = soapFaultException.getFault().getFaultString();
        faultActor = soapFaultException.getFault().getFaultActor();
    }
    if (faultCode == null) {
        faultCode = getDefaultFaultCode(soapVersion);
    }
    if (faultString == null) {
        faultString = e.getMessage();
        if (faultString == null) {
            faultString = e.toString();
        }
    }
    Element detailNode = null;
    QName firstEntry = null;
    if (detail == null && soapFaultException != null) {
        detailNode = soapFaultException.getFault().getDetail();
        firstEntry = getFirstDetailEntryName((Detail) detailNode);
    } else if (ce != null) {
        try {
            DOMResult dr = new DOMResult();
            ce.getBridge().marshal(detail, dr);
            detailNode = (Element) dr.getNode().getFirstChild();
            firstEntry = getFirstDetailEntryName(detailNode);
        } catch (JAXBException e1) {
            faultString = e.getMessage();
            faultCode = getDefaultFaultCode(soapVersion);
        }
    }
    SOAP11Fault soap11Fault = new SOAP11Fault(faultCode, faultString, faultActor, detailNode);
    soap11Fault.captureStackTrace(e);
    Message msg = JAXBMessage.create(JAXB_CONTEXT, soap11Fault, soapVersion);
    return new FaultMessage(msg, firstEntry);
}
Example 28
Project: ManagedRuntimeInitiative-master  File: SOAPFaultBuilder.java View source code
private static Message createSOAP11Fault(SOAPVersion soapVersion, Throwable e, Object detail, CheckedExceptionImpl ce, QName faultCode) {
    SOAPFaultException soapFaultException = null;
    String faultString = null;
    String faultActor = null;
    Throwable cause = e.getCause();
    if (e instanceof SOAPFaultException) {
        soapFaultException = (SOAPFaultException) e;
    } else if (cause != null && cause instanceof SOAPFaultException) {
        soapFaultException = (SOAPFaultException) e.getCause();
    }
    if (soapFaultException != null) {
        QName soapFaultCode = soapFaultException.getFault().getFaultCodeAsQName();
        if (soapFaultCode != null)
            faultCode = soapFaultCode;
        faultString = soapFaultException.getFault().getFaultString();
        faultActor = soapFaultException.getFault().getFaultActor();
    }
    if (faultCode == null) {
        faultCode = getDefaultFaultCode(soapVersion);
    }
    if (faultString == null) {
        faultString = e.getMessage();
        if (faultString == null) {
            faultString = e.toString();
        }
    }
    Element detailNode = null;
    if (detail == null && soapFaultException != null) {
        detailNode = soapFaultException.getFault().getDetail();
    } else if (ce != null) {
        try {
            DOMResult dr = new DOMResult();
            ce.getBridge().marshal(detail, dr);
            detailNode = (Element) dr.getNode().getFirstChild();
        } catch (JAXBException e1) {
            faultString = e.getMessage();
            faultCode = getDefaultFaultCode(soapVersion);
        }
    }
    SOAP11Fault soap11Fault = new SOAP11Fault(faultCode, faultString, faultActor, detailNode);
    soap11Fault.captureStackTrace(e);
    return JAXBMessage.create(JAXB_CONTEXT, soap11Fault, soapVersion);
}
Example 29
Project: Payara-master  File: SOAPWebConsumer.java View source code
private void addUsingSOAPConsumer() {
    com.example.calculator.Calculator port = null;
    port = service.getCalculatorPort();
    // Get Stub
    BindingProvider stub = (BindingProvider) port;
    String endpointURI = "http://localhost:12011/calculatorendpoint";
    stub.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURI);
    String failedMsg = null;
    try {
        System.out.println("\nInvoking throwRuntimeException");
        port.throwRuntimeException("bhavani");
    } catch (Exception ex) {
        System.out.println(ex);
        if (!(ex instanceof SOAPFaultException) || !(ex.getMessage().equals("java.lang.RuntimeException: Calculator :: Threw Runtime Exception"))) {
            failedMsg = "port.throwRuntimeException() did not receive RuntimeException 'Calculator :: Threw Runtime Exception'";
        }
    }
    try {
        System.out.println("\nInvoking throwApplicationException");
        port.throwApplicationException("bhavani");
    } catch (Exception ex) {
        System.out.println(ex);
        if (!(ex instanceof com.example.calculator.Exception_Exception)) {
            failedMsg = "port.throwApplicationException() did not throw ApplicationException";
        }
    }
    if (failedMsg != null) {
        stat.addStatus(testId, stat.FAIL);
    } else {
        stat.addStatus(testId, stat.PASS);
    }
}
Example 30
Project: BridgeDb-master  File: PICRSequenceDemo.java View source code
public void actionPerformed(ActionEvent e) {
    try {
        if (!"".equals(sequenceArea.getText())) {
            java.util.List<UPEntry> entries = client.performSequenceMapping(sequenceArea.getText(), databaseList.getSelectedValues());
            //compute size of arary
            if (entries != null) {
                int size = 0;
                for (UPEntry entry : entries) {
                    for (CrossReference xref : entry.getIdenticalCrossReferences()) {
                        size++;
                    }
                    for (CrossReference xref : entry.getLogicalCrossReferences()) {
                        size++;
                    }
                }
                if (size > 0) {
                    final Object[][] data = new Object[size][4];
                    int i = 0;
                    for (UPEntry entry : entries) {
                        for (CrossReference xref : entry.getIdenticalCrossReferences()) {
                            data[i][0] = xref.getDatabaseName();
                            data[i][1] = xref.getAccession();
                            data[i][2] = xref.getAccessionVersion();
                            data[i][3] = xref.getTaxonId();
                            i++;
                        }
                        for (CrossReference xref : entry.getLogicalCrossReferences()) {
                            data[i][0] = xref.getDatabaseName();
                            data[i][1] = xref.getAccession();
                            data[i][2] = xref.getAccessionVersion();
                            data[i][3] = xref.getTaxonId();
                            i++;
                        }
                    }
                    //refresh
                    DefaultTableModel dataModel = new DefaultTableModel();
                    dataModel.setDataVector(data, columns);
                    dataTable.setModel(dataModel);
                    System.out.println("update done");
                } else {
                    JOptionPane.showMessageDialog(null, "No Mappind data found.");
                }
            } else {
                JOptionPane.showMessageDialog(null, "No Mappind data found.");
            }
        } else {
            JOptionPane.showMessageDialog(null, "You must enter a valid FASTA sequence to map.");
        }
    } catch (SOAPFaultException soapEx) {
        JOptionPane.showMessageDialog(null, "A SOAP Error occurred.");
        soapEx.printStackTrace();
    }
}
Example 31
Project: federation-master  File: STSSaml20HandlerTestCase.java View source code
@Test
public void handleMessageInValidToken() throws Exception {
    when(wsTrustClient.validateToken((any(Element.class)))).thenReturn(false);
    final SOAPHeaderElement securityHeader = addSecurityHeader(soapMessage.getSOAPHeader());
    addSecurityAssertionElement(securityHeader);
    when(soapMessageContext.get(MESSAGE_OUTBOUND_PROPERTY)).thenReturn(false);
    when(soapMessageContext.getMessage()).thenReturn(soapMessage);
    try {
        samlHandler.handleMessage(soapMessageContext);
        fail("handleMessage should have thrown an exception");
    } catch (final Exception e) {
        assertTrue(e instanceof SOAPFaultException);
        assertSoapFaultString(e, "The security token could not be authenticated or authorized");
    }
}
Example 32
Project: jboss-fuse-examples-master  File: WsHelloWorldServiceTest.java View source code
@Test(expected = SOAPFaultException.class)
public void throwsExceptionDueToMissingClientAlias() throws InvalidObjectException {
    HelloWorldRequest request = new HelloWorldRequest();
    request.setHello("bob");
    WsEndpointConfiguration<HelloWorldEndpoint> config = getDefaultConfig();
    config.setCertifactionAlias("");
    WsHelloWorldService service = new WsHelloWorldService(config, isCxfBeanFactory());
    service.sayHello(request);
}
Example 33
Project: jiolsucker-master  File: SharepointIolDAO.java View source code
@Override
public void run() {
    try {
        final WebListing sub = getWebs(new FixedURISharepointStrategy(URI.create(web.getUrl())), serviceFactory);
        for (final SWebWithTime s : sub.getWebs()) {
            executorService.execute(new Runnable() {

                @Override
                public void run() {
                    final WebListing subsub = getWebs(new FixedURISharepointStrategy(URI.create(s.getUrl())), serviceFactory);
                    final String[] uriTitle = new String[] { s.getUrl(), subsub.getMetadata().getTitle() };
                    materiasUrlTitle.add(uriTitle);
                }
            });
        }
    } catch (SOAPFaultException t) {
    }
}
Example 34
Project: koku-ui-master  File: UserSearchController.java View source code
@RenderMapping(params = "action=searchUserParams")
public String renderParams(PortletSession session, @RequestParam(value = "pic", required = false) String pic, @RequestParam(value = "picSelection", required = false) String picSelection, RenderRequest req, RenderResponse res, Model model) {
    User customer = null;
    // add logging mode for LOK to model
    boolean picCheck = false;
    // get user pic and role
    String userSessionPic = LogUtils.getPicFromSession(session);
    List<Role> userRoles = authorizationInfoService.getUsersRoles(LogConstants.COMPONENT_LOK, userSessionPic);
    // search.jsp
    if (AuthUtils.isOperationAllowed("AdminSystemLogFile", userRoles)) {
        model.addAttribute("allowedToView", true);
    }
    model.addAttribute("picType", picSelection == null ? DEFAULT_PIC : picSelection);
    // see http://fi.wikipedia.org/wiki/Henkil%C3%B6tunnus#Tunnuksen_muoto
    if (pic != null && pic.length() == 11 && (pic.charAt(6) == '-' || pic.charAt(6) == '+' || pic.charAt(6) == 'A')) {
        // pic is well formed
        picCheck = true;
    }
    if (picCheck) {
        try {
            customer = findUser(pic, userSessionPic, picSelection != null && picSelection.equals("customerPic"));
        } catch (ServiceFault fault) {
            if (fault.getMessage().equalsIgnoreCase("Customer not found.")) {
                model.addAttribute("error", "koku.lok.no.user.results");
            } else {
                model.addAttribute("error", "koku.lok.error.customer");
            }
            log.error("servicefault");
            log.error(fault.getMessage());
        } catch (SOAPFaultException e) {
            log.error("SOAPFaultException: " + e.getMessage());
            model.addAttribute("error", "koku.lok.error.customer");
        }
        if (customer != null) {
            model.addAttribute("searchedUsers", customer);
            model.addAttribute("foundName", customer.getSname() + " " + customer.getFname());
            model.addAttribute("foundPic", customer.getPic());
        } else {
            model.addAttribute("error", "koku.lok.no.user.results");
        }
    } else {
        // pic is not well formed
        model.addAttribute("error", "koku.lok.malformed.pic");
    }
    // This means that search was done
    model.addAttribute("search", true);
    return "usersearch";
}
Example 35
Project: midpoint-master  File: TestWSSecurity.java View source code
@Test
public void test100GetConfigNoSecurity() throws Exception {
    final String TEST_NAME = "test100GetConfigNoSecurity";
    displayTestTitle(TEST_NAME);
    LogfileTestTailer tailer = createLogTailer();
    modelPort = createModelPort(null, null);
    Holder<ObjectType> objectHolder = new Holder<ObjectType>();
    Holder<OperationResultType> resultHolder = new Holder<OperationResultType>();
    // WHEN
    try {
        modelPort.getObject(getTypeQName(SystemConfigurationType.class), SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, objectHolder, resultHolder);
        AssertJUnit.fail("Unexpected success");
    } catch (SOAPFaultException e) {
        assertSoapSecurityFault(e, "InvalidSecurity", "<wsse:Security> header");
    }
    tailer.tail();
    assertAuditLoginFailed(tailer, "<wsse:Security> header");
}
Example 36
Project: openbel-framework-experimental  File: TestEndPointKamHandleValidation.java View source code
private <T> void check(final String apiMethodName, final T request, final String setHandleMethodName) {
    Method apiMethod = null;
    Method setHandle = null;
    try {
        apiMethod = WebAPI.class.getDeclaredMethod(apiMethodName, request.getClass());
        setHandle = request.getClass().getDeclaredMethod(setHandleMethodName, KamHandle.class);
    } catch (NoSuchMethodException e) {
        fail("Caught NoSuchMethodException:  " + e.getMessage());
        return;
    } catch (SecurityException e) {
        fail("Caught SecurityException:  " + e.getMessage());
        return;
    }
    try {
        setHandle.invoke(request, invalidKamHandle);
        apiMethod.invoke(webAPI, request);
    } catch (IllegalAccessException e) {
        fail("Caught IllegalAccessException:  " + e.getMessage());
    } catch (IllegalArgumentException e) {
        fail("Caught IllegalArgumentException:  " + e.getMessage());
    } catch (InvocationTargetException e) {
        final Throwable cause = e.getCause();
        if (cause instanceof SOAPFaultException) {
            final SOAPFaultException ex = (SOAPFaultException) cause;
            final SOAPFault fault = ex.getFault();
            assertThat(fault, is(not(nullValue())));
            final String faultString = fault.getFaultString();
            assertThat(faultString, is(not(nullValue())));
            assertThat(faultString, containsString(invalidKamHandleName));
        } else {
            fail("Caught InvocationTargetException:  " + e.getMessage());
        }
    }
}
Example 37
Project: openjdk-master  File: ResponseBuilder.java View source code
private SOAPFaultException createDuplicateHeaderException() {
    try {
        SOAPFault fault = soapVersion.getSOAPFactory().createFault();
        fault.setFaultCode(soapVersion.faultCodeServer);
        fault.setFaultString(ServerMessages.DUPLICATE_PORT_KNOWN_HEADER(headerName));
        return new SOAPFaultException(fault);
    } catch (SOAPException e) {
        throw new WebServiceException(e);
    }
}
Example 38
Project: picketlink-master  File: STSSaml20HandlerTestCase.java View source code
@Test
public void handleMessageInValidToken() throws Exception {
    when(wsTrustClient.validateToken((any(Element.class)))).thenReturn(false);
    final SOAPHeaderElement securityHeader = addSecurityHeader(soapMessage.getSOAPHeader());
    addSecurityAssertionElement(securityHeader);
    when(soapMessageContext.get(MESSAGE_OUTBOUND_PROPERTY)).thenReturn(false);
    when(soapMessageContext.getMessage()).thenReturn(soapMessage);
    try {
        samlHandler.handleMessage(soapMessageContext);
        fail("handleMessage should have thrown an exception");
    } catch (final Exception e) {
        assertTrue(e instanceof SOAPFaultException);
        assertSoapFaultString(e, "The security token could not be authenticated or authorized");
    }
}
Example 39
Project: siu-master  File: SmevInteraction.java View source code
private String createSoapFaultMessage(SOAPFaultException failure) {
    SOAPFault fault = failure.getFault();
    StringBuilder message = new StringBuilder("Ошибка взаимодейÑ?твиÑ? Ñ? поÑ?тавщиком уÑ?луги");
    Name code = fault.getFaultCodeAsName();
    if (code != null) {
        message.append(" (").append(code.getLocalName()).append(')');
    }
    message.append(":\n");
    message.append(fault.getFaultString());
    return message.toString();
}
Example 40
Project: tropo-servlet-master  File: ThriftAppMgr.java View source code
protected void authenticate(BindStruct bind) throws AuthenticationException, SystemException {
    if (bind.getAccountId() <= 0 || StringUtils.isEmpty(bind.getApplicationId())) {
        throw new SystemException("Invalid account or application.");
    }
    try {
        String token = Utils.authenticate(_authenticationServer, bind.getUser(), bind.getPassword());
    } catch (SOAPFaultException e) {
        if (e.getMessage().contains("Invalid login")) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Invalid username[" + bind.getUser() + "] or password[" + bind.getPassword() + "]");
            }
            throw new AuthenticationException("Invalid username[" + bind.getUser() + "] or password[" + bind.getPassword() + "]");
        } else {
            LOG.error(e.toString(), e);
            throw new SystemException(e.getMessage());
        }
    } catch (Exception e) {
        LOG.error(e.toString(), e);
        throw new SystemException(e.getMessage());
    }
}
Example 41
Project: bioknime-master  File: InterProScanNodeModel.java View source code
private String submit_job_async(IPRScanClient cli, String email_address, String seq, String rkey, ObjectFactory of) throws Exception {
    for (int retry = 0; retry < 4; retry++) {
        try {
            InputParameters job_params = new InputParameters();
            ArrayOfString aos = new ArrayOfString();
            for (String appl : m_vec.getStringArrayValue()) {
                aos.getString().add(appl.toLowerCase());
            }
            job_params.setAppl(of.createInputParametersAppl(aos));
            job_params.setSequence(of.createInputParametersSequence(seq));
            job_params.setGoterms(of.createInputParametersGoterms(new Boolean(true)));
            job_params.setNocrc(of.createInputParametersNocrc(new Boolean(!m_crc.getBooleanValue())));
            return cli.runApp(m_email.getStringValue(), rkey, job_params);
        } catch (RemoteException re) {
            throw re;
        } catch (ServiceException se) {
            throw se;
        } catch (SOAPFaultException soape) {
            throw soape;
        } catch (Exception e) {
            int delay = (retry + 1) * 500;
            logger.warn("Problem when submitting job: " + e.getMessage() + "... retrying in " + delay + " seconds");
            Thread.sleep(delay * 1000);
        }
    }
    throw new FailedJobException("Cannot submit job after four attempts... giving up on " + rkey + "!");
}
Example 42
Project: coverity-plugin-master  File: CIMInstance.java View source code
public FormValidation doCheck() throws IOException {
    StringBuilder errorMessage = new StringBuilder();
    errorMessage.append("\"" + user + "\" does not have following permission(s): ");
    try {
        URL url = WebServiceFactory.getInstance().getURL(this);
        int responseCode = getURLResponseCode(new URL(url, WebServiceFactory.CONFIGURATION_SERVICE_V9_WSDL));
        if (responseCode != 200) {
            return FormValidation.error("Coverity web services were not detected. Connection attempt responded with " + responseCode + ", check Coverity Connect version (minimum supported version is " + CoverityVersion.MINIMUM_SUPPORTED_VERSION.getEffectiveVersion().getEffectiveVersion() + ").");
        }
        List<String> missingPermission = new ArrayList<String>();
        if (!checkUserPermission(missingPermission, false) && !missingPermission.isEmpty()) {
            for (String permission : missingPermission) {
                errorMessage.append("\"" + permission + "\" ");
            }
            return FormValidation.error(errorMessage.toString());
        }
        // check for missing global permissions to warn users
        //   in some cases users could have group permissions but only a specific project, stream, etc.
        List<String> missingGlobalPermission = new ArrayList<String>();
        if (!checkUserPermission(missingGlobalPermission, true) && !missingGlobalPermission.isEmpty()) {
            StringBuilder warningMessage = new StringBuilder();
            warningMessage.append("\"" + user + "\" does not have following global permission(s): ");
            for (String permission : missingGlobalPermission) {
                warningMessage.append("\"" + permission + "\" ");
            }
            return FormValidation.warning(warningMessage.toString());
        }
        return FormValidation.ok("Successfully connected to the instance.");
    } catch (UnknownHostException e) {
        return FormValidation.error("Host name unknown");
    } catch (ConnectException e) {
        return FormValidation.error("Connection refused");
    } catch (SocketException e) {
        return FormValidation.error("Error connecting to CIM. Please check your connection settings.");
    } catch (SOAPFaultException e) {
        if (StringUtils.isNotEmpty(e.getMessage())) {
            if (e.getMessage().contains("User " + user + " Doesn't have permissions to perform {invokeWS}")) {
                return FormValidation.error(errorMessage.append("\"Access web services\"").toString());
            }
            return FormValidation.error(e.getMessage());
        }
        return FormValidation.error(e, "An unexpected error occurred.");
    } catch (Throwable e) {
        String javaVersion = System.getProperty("java.version");
        if (javaVersion.startsWith("1.6.0_")) {
            int patch = Integer.parseInt(javaVersion.substring(javaVersion.indexOf('_') + 1));
            if (patch < 26) {
                return FormValidation.error(e, "Please use Java 1.6.0_26 or later to run Jenkins.");
            }
        }
        return FormValidation.error(e, "An unexpected error occurred.");
    }
}
Example 43
Project: eclipselink.runtime-master  File: SecondarySQLTestSuite.java View source code
@Test
public void countSecondary() throws SOAPException, SAXException, IOException, TransformerException {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage request = factory.createMessage();
    SOAPPart part = request.getSOAPPart();
    DOMSource domSource = new DOMSource(getDocumentBuilder().parse(new InputSource(new StringReader(COUNT_REQUEST_MSG))));
    part.setContent(domSource);
    Dispatch<SOAPMessage> dispatch = testService.createDispatch(portQName, SOAPMessage.class, Service.Mode.MESSAGE);
    SOAPMessage response = null;
    try {
        response = dispatch.invoke(request);
    } catch (SOAPFaultException sfe) {
        sfe.printStackTrace();
    }
    if (response != null) {
        Source src = response.getSOAPPart().getContent();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMResult result = new DOMResult();
        transformer.transform(src, result);
        Document resultDoc = (Document) result.getNode();
        Document controlDoc = xmlParser.parse(new StringReader(COUNT_RESPONSE_MSG));
        assertTrue("control document not same as instance document", comparer.isNodeEqual(controlDoc, resultDoc));
    }
}
Example 44
Project: fosstrak-fc-master  File: ALEClient.java View source code
@Override
protected void executeCommand() {
    Object result = null;
    String specName = null;
    String notificationURI = null;
    Exception ex = null;
    try {
        switch(m_commandSelection.getSelectedIndex()) {
            case // getECSpecNames
            CMD__GET_ECSPEC_NAMES:
                result = getAleServiceProxy().getECSpecNames(new EmptyParms());
                break;
            case // getStandardVersion
            CMD__GET_STANDARD_VERSION:
                result = getAleServiceProxy().getStandardVersion(new EmptyParms());
                break;
            case // getVendorVersion
            CMD__GET_VENDOR_VERSION:
                result = getAleServiceProxy().getVendorVersion(new EmptyParms());
                break;
            // undefine
            case CMD__UNDEFINE:
            // getECSpec
            case CMD__GET_ECSPEC:
            case // poll
            CMD__POLL:
            case // getSubscribers
            CMD__GET_SUBSCRIBERS:
                // get specName
                specName = (String) m_specNameComboBox.getSelectedItem();
                if (specName == null || "".equals(specName)) {
                    FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("SpecNameNotSpecifiedDialog"));
                    break;
                }
                switch(m_commandSelection.getSelectedIndex()) {
                    case // undefine
                    CMD__UNDEFINE:
                        Undefine undefineParms = new Undefine();
                        undefineParms.setSpecName(specName);
                        getAleServiceProxy().undefine(undefineParms);
                        result = m_guiText.getString("SuccessfullyUndefinedMessage");
                        break;
                    case CMD__GET_ECSPEC// getECSpec
                    :
                        GetECSpec getECSpecParms = new GetECSpec();
                        getECSpecParms.setSpecName(specName);
                        result = getAleServiceProxy().getECSpec(getECSpecParms);
                        break;
                    case // poll
                    CMD__POLL:
                        Poll pollParms = new Poll();
                        pollParms.setSpecName(specName);
                        result = getAleServiceProxy().poll(pollParms);
                        break;
                    case // getSubscribers
                    CMD__GET_SUBSCRIBERS:
                        GetSubscribers getSubscribersParms = new GetSubscribers();
                        getSubscribersParms.setSpecName(specName);
                        result = getAleServiceProxy().getSubscribers(getSubscribersParms);
                        break;
                }
                break;
            // subscribe
            case CMD__SUBSCRIBE:
            case // unsubscribe
            CMD__UNSUBSCRIBE:
                // get specName
                specName = (String) m_specNameComboBox.getSelectedItem();
                if (specName == null || "".equals(specName)) {
                    FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("SpecNameNotSpecifiedDialog"));
                    break;
                }
                switch(m_commandSelection.getSelectedIndex()) {
                    case CMD__SUBSCRIBE:
                        // get notificationURI
                        notificationURI = m_notificationUriField.getText();
                        if (notificationURI == null || "".equals(notificationURI)) {
                            FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("NotificationUriNotSpecifiedDialog"));
                            break;
                        }
                        if (m_createEventSink.isSelected()) {
                            createEventSink(m_notificationUriField.getText());
                        }
                        Subscribe subscribeParms = new Subscribe();
                        subscribeParms.setSpecName(specName);
                        subscribeParms.setNotificationURI(notificationURI);
                        getAleServiceProxy().subscribe(subscribeParms);
                        result = m_guiText.getString("SuccessfullySubscribedMessage");
                        break;
                    case CMD__UNSUBSCRIBE:
                        // get notificationURI
                        notificationURI = (String) m_subscribersComboBox.getSelectedItem();
                        if (notificationURI == null || "".equals(notificationURI)) {
                            FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("NotificationUriNotSpecifiedDialog"));
                            break;
                        }
                        Unsubscribe unsubscribeParms = new Unsubscribe();
                        unsubscribeParms.setSpecName(specName);
                        unsubscribeParms.setNotificationURI(notificationURI);
                        getAleServiceProxy().unsubscribe(unsubscribeParms);
                        result = m_guiText.getString("SuccessfullyUnsubscribedMessage");
                        break;
                }
                break;
            case CMD__DEFINE// define
            :
            case // immediate
            CMD__IMMEDIATE:
                if (m_commandSelection.getSelectedIndex() == CMD__DEFINE) {
                    // get specName
                    specName = m_specNameValueField.getText();
                    if (specName == null || "".equals(specName)) {
                        FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("SpecNameNotSpecifiedDialog"));
                        break;
                    }
                }
                // get filePath
                String filePath = m_filePathField.getText();
                if (filePath == null || "".equals(filePath)) {
                    FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("FilePathNotSpecifiedDialog"));
                    break;
                }
                // get ecSpec
                ECSpec ecSpec;
                try {
                    ecSpec = getECSpecFromFile(filePath);
                } catch (FileNotFoundException e) {
                    FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("FileNotFoundDialog"));
                    ex = e;
                    break;
                } catch (Exception e) {
                    FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("UnexpectedFileFormatDialog"));
                    ex = e;
                    break;
                }
                if (m_commandSelection.getSelectedIndex() == CMD__DEFINE) {
                    Define defineParms = new Define();
                    defineParms.setSpecName(specName);
                    defineParms.setSpec(ecSpec);
                    getAleServiceProxy().define(defineParms);
                    result = m_guiText.getString("SuccessfullyDefinedMessage");
                } else {
                    Immediate immediateParms = new Immediate();
                    immediateParms.setSpec(ecSpec);
                    result = getAleServiceProxy().immediate(immediateParms);
                }
                break;
        }
    } catch (Exception e) {
        String reason = e.getMessage();
        String text = "Unknown Error";
        if (e instanceof DuplicateNameExceptionResponse) {
            text = m_guiText.getString("DuplicateNameExceptionDialog");
        } else if (e instanceof DuplicateSubscriptionExceptionResponse) {
            text = m_guiText.getString("DuplicateSubscriptionExceptionDialog");
        } else if (e instanceof ECSpecValidationExceptionResponse) {
            text = m_guiText.getString("ECSpecValidationExceptionDialog");
        } else if (e instanceof ImplementationExceptionResponse) {
            text = m_guiText.getString("ImplementationExceptionDialog");
        } else if (e instanceof InvalidURIExceptionResponse) {
            text = m_guiText.getString("InvalidURIExceptionDialog");
        } else if (e instanceof NoSuchNameExceptionResponse) {
            text = m_guiText.getString("NoSuchNameExceptionDialog");
        } else if (e instanceof NoSuchSubscriberExceptionResponse) {
            text = m_guiText.getString("NoSuchSubscriberExceptionDialog");
        } else if (e instanceof SecurityExceptionResponse) {
            text = m_guiText.getString("SecurityExceptionDialog");
        } else if (e instanceof SOAPFaultException) {
            text = "Service error";
        } else if (e instanceof FosstrakAleClientServiceDownException) {
            text = "Unable to execute command.";
            reason = "Service is down or endpoint wrong.";
        }
        FosstrakAleClient.instance().showExceptionDialog(text, reason);
        ex = e;
    }
    if (null == ex) {
        showResult(result);
    } else {
        showResult(ex);
    }
    // update spec name combobox
    List<String> ecSpecNames = null;
    try {
        ecSpecNames = getAleServiceProxy().getECSpecNames(new EmptyParms()).getString();
    } catch (Exception e) {
    }
    if (ecSpecNames != null && m_specNameComboBox != null && m_specNameComboBox.getSelectedObjects() != null && m_specNameComboBox.getSelectedObjects().length > 0) {
        String current = (String) m_specNameComboBox.getSelectedObjects()[0];
        m_specNameComboBox.removeAllItems();
        if (ecSpecNames != null && ecSpecNames.size() > 0) {
            for (String name : ecSpecNames) {
                m_specNameComboBox.addItem(name);
            }
        }
        m_specNameComboBox.setSelectedItem(current);
    }
}
Example 45
Project: geo-platform-master  File: SecurityService.java View source code
@Override
public IGPAccountDetail userLogin(String username, String password, Long projectID, HttpServletRequest httpServletRequest) throws GeoPlatformException {
    GPUser user;
    try {
        user = geoPlatformServiceClient.getUserDetailByUsernameAndPassword(username, password);
        return this.executeLoginOnGPAccount(user, geoPlatformServiceClient.getAccountPermission(user.getId()), projectID, httpServletRequest);
    } catch (ResourceNotFoundFault ex) {
        logger.error("SecurityService", "Unable to find user with username or email: " + username + " Error: " + ex);
        throw new GeoPlatformException("Unable to find user with username or email: " + username);
    } catch (SOAPFaultException ex) {
        logger.error("Error on SecurityService: " + ex + " password incorrect");
        throw new GeoPlatformException("Password incorrect");
    } catch (IllegalParameterFault ex) {
        logger.error("Error on SecurityService: " + ex);
        throw new GeoPlatformException("Parameter incorrect");
    } catch (AccountLoginFault ex) {
        logger.error("Error on SecurityService: " + ex);
        throw new GeoPlatformException(ex.getMessage() + ", contact the administrator");
    }
}
Example 46
Project: oliot-fc-master  File: ALEClient.java View source code
@Override
protected void executeCommand() {
    Object result = null;
    String specName = null;
    String notificationURI = null;
    Exception ex = null;
    try {
        switch(m_commandSelection.getSelectedIndex()) {
            case // getECSpecNames
            CMD__GET_ECSPEC_NAMES:
                result = getAleServiceProxy().getECSpecNames(new EmptyParms());
                break;
            case // getStandardVersion
            CMD__GET_STANDARD_VERSION:
                result = getAleServiceProxy().getStandardVersion(new EmptyParms());
                break;
            case // getVendorVersion
            CMD__GET_VENDOR_VERSION:
                result = getAleServiceProxy().getVendorVersion(new EmptyParms());
                break;
            // undefine
            case CMD__UNDEFINE:
            // getECSpec
            case CMD__GET_ECSPEC:
            case // poll
            CMD__POLL:
            case // getSubscribers
            CMD__GET_SUBSCRIBERS:
                // get specName
                specName = (String) m_specNameComboBox.getSelectedItem();
                if (specName == null || "".equals(specName)) {
                    FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("SpecNameNotSpecifiedDialog"));
                    break;
                }
                switch(m_commandSelection.getSelectedIndex()) {
                    case // undefine
                    CMD__UNDEFINE:
                        Undefine undefineParms = new Undefine();
                        undefineParms.setSpecName(specName);
                        getAleServiceProxy().undefine(undefineParms);
                        result = m_guiText.getString("SuccessfullyUndefinedMessage");
                        break;
                    case CMD__GET_ECSPEC// getECSpec
                    :
                        GetECSpec getECSpecParms = new GetECSpec();
                        getECSpecParms.setSpecName(specName);
                        result = getAleServiceProxy().getECSpec(getECSpecParms);
                        break;
                    case // poll
                    CMD__POLL:
                        Poll pollParms = new Poll();
                        pollParms.setSpecName(specName);
                        result = getAleServiceProxy().poll(pollParms);
                        break;
                    case // getSubscribers
                    CMD__GET_SUBSCRIBERS:
                        GetSubscribers getSubscribersParms = new GetSubscribers();
                        getSubscribersParms.setSpecName(specName);
                        result = getAleServiceProxy().getSubscribers(getSubscribersParms);
                        break;
                }
                break;
            // subscribe
            case CMD__SUBSCRIBE:
            case // unsubscribe
            CMD__UNSUBSCRIBE:
                // get specName
                specName = (String) m_specNameComboBox.getSelectedItem();
                if (specName == null || "".equals(specName)) {
                    FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("SpecNameNotSpecifiedDialog"));
                    break;
                }
                switch(m_commandSelection.getSelectedIndex()) {
                    case CMD__SUBSCRIBE:
                        // get notificationURI
                        notificationURI = m_notificationUriField.getText();
                        if (notificationURI == null || "".equals(notificationURI)) {
                            FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("NotificationUriNotSpecifiedDialog"));
                            break;
                        }
                        if (m_createEventSink.isSelected()) {
                            createEventSink(m_notificationUriField.getText());
                        }
                        Subscribe subscribeParms = new Subscribe();
                        subscribeParms.setSpecName(specName);
                        subscribeParms.setNotificationURI(notificationURI);
                        getAleServiceProxy().subscribe(subscribeParms);
                        result = m_guiText.getString("SuccessfullySubscribedMessage");
                        break;
                    case CMD__UNSUBSCRIBE:
                        // get notificationURI
                        notificationURI = (String) m_subscribersComboBox.getSelectedItem();
                        if (notificationURI == null || "".equals(notificationURI)) {
                            FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("NotificationUriNotSpecifiedDialog"));
                            break;
                        }
                        Unsubscribe unsubscribeParms = new Unsubscribe();
                        unsubscribeParms.setSpecName(specName);
                        unsubscribeParms.setNotificationURI(notificationURI);
                        getAleServiceProxy().unsubscribe(unsubscribeParms);
                        result = m_guiText.getString("SuccessfullyUnsubscribedMessage");
                        break;
                }
                break;
            case CMD__DEFINE// define
            :
            case // immediate
            CMD__IMMEDIATE:
                if (m_commandSelection.getSelectedIndex() == CMD__DEFINE) {
                    // get specName
                    specName = m_specNameValueField.getText();
                    if (specName == null || "".equals(specName)) {
                        FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("SpecNameNotSpecifiedDialog"));
                        break;
                    }
                }
                // get filePath
                String filePath = m_filePathField.getText();
                if (filePath == null || "".equals(filePath)) {
                    FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("FilePathNotSpecifiedDialog"));
                    break;
                }
                // get ecSpec
                ECSpec ecSpec;
                try {
                    ecSpec = getECSpecFromFile(filePath);
                } catch (FileNotFoundException e) {
                    FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("FileNotFoundDialog"));
                    ex = e;
                    break;
                } catch (Exception e) {
                    FosstrakAleClient.instance().showExceptionDialog(m_guiText.getString("UnexpectedFileFormatDialog"));
                    ex = e;
                    break;
                }
                if (m_commandSelection.getSelectedIndex() == CMD__DEFINE) {
                    Define defineParms = new Define();
                    defineParms.setSpecName(specName);
                    defineParms.setSpec(ecSpec);
                    getAleServiceProxy().define(defineParms);
                    result = m_guiText.getString("SuccessfullyDefinedMessage");
                } else {
                    Immediate immediateParms = new Immediate();
                    immediateParms.setSpec(ecSpec);
                    result = getAleServiceProxy().immediate(immediateParms);
                }
                break;
        }
    } catch (Exception e) {
        String reason = e.getMessage();
        String text = "Unknown Error";
        if (e instanceof DuplicateNameExceptionResponse) {
            text = m_guiText.getString("DuplicateNameExceptionDialog");
        } else if (e instanceof DuplicateSubscriptionExceptionResponse) {
            text = m_guiText.getString("DuplicateSubscriptionExceptionDialog");
        } else if (e instanceof ECSpecValidationExceptionResponse) {
            text = m_guiText.getString("ECSpecValidationExceptionDialog");
        } else if (e instanceof ImplementationExceptionResponse) {
            text = m_guiText.getString("ImplementationExceptionDialog");
        } else if (e instanceof InvalidURIExceptionResponse) {
            text = m_guiText.getString("InvalidURIExceptionDialog");
        } else if (e instanceof NoSuchNameExceptionResponse) {
            text = m_guiText.getString("NoSuchNameExceptionDialog");
        } else if (e instanceof NoSuchSubscriberExceptionResponse) {
            text = m_guiText.getString("NoSuchSubscriberExceptionDialog");
        } else if (e instanceof SecurityExceptionResponse) {
            text = m_guiText.getString("SecurityExceptionDialog");
        } else if (e instanceof SOAPFaultException) {
            text = "Service error";
        } else if (e instanceof FosstrakAleClientServiceDownException) {
            text = "Unable to execute command.";
            reason = "Service is down or endpoint wrong.";
        }
        FosstrakAleClient.instance().showExceptionDialog(text, reason);
        ex = e;
    }
    if (null == ex) {
        showResult(result);
    } else {
        showResult(ex);
    }
    // update spec name combobox
    List<String> ecSpecNames = null;
    try {
        ecSpecNames = getAleServiceProxy().getECSpecNames(new EmptyParms()).getString();
    } catch (Exception e) {
    }
    if (ecSpecNames != null && m_specNameComboBox != null && m_specNameComboBox.getSelectedObjects() != null && m_specNameComboBox.getSelectedObjects().length > 0) {
        String current = (String) m_specNameComboBox.getSelectedObjects()[0];
        m_specNameComboBox.removeAllItems();
        if (ecSpecNames != null && ecSpecNames.size() > 0) {
            for (String name : ecSpecNames) {
                m_specNameComboBox.addItem(name);
            }
        }
        m_specNameComboBox.setSelectedItem(current);
    }
}
Example 47
Project: sf-api-connector-master  File: MetadataConnectionImplTest.java View source code
private static void assertInvalidSession(ApiException e) {
    assertEquals("Call failed", e.getMessage());
    Throwable cause = e.getCause();
    assertTrue(cause instanceof SOAPFaultException);
    SOAPFaultException soapFaultException = (SOAPFaultException) cause;
    String expectedMsg = "INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session. Session not found, missing session key: ";
    String actualMsg = soapFaultException.getMessage();
    assertEquals(expectedMsg, truncateSessionId(actualMsg));
    SOAPFault fault = soapFaultException.getFault();
    QName codeQname = fault.getFaultCodeAsQName();
    assertEquals("INVALID_SESSION_ID", codeQname.getLocalPart());
    String faultMsg = fault.getFaultString();
    assertEquals(expectedMsg, truncateSessionId(faultMsg));
}
Example 48
Project: sitewhere-magento-master  File: MagentoAssetModule.java View source code
/**
	 * Logs in to Magento and saves the session id.
	 * 
	 * @throws SiteWhereException
	 */
protected void login() throws SiteWhereException {
    LoginParam loginParams = new LoginParam();
    loginParams.setUsername(getMagentoUsername());
    loginParams.setApiKey(getMagentoPassword());
    try {
        LoginResponseParam loginResponse = port.login(loginParams);
        sessionId = loginResponse.getResult();
    } catch (SOAPFaultException e) {
        throw new SiteWhereException("Magento login failed.", e);
    }
}
Example 49
Project: spring-framework-2.5.x-master  File: JaxWsPortClientInterceptor.java View source code
/**
	 * Perform a JAX-WS service invocation based on the given method invocation.
	 * @param invocation the AOP method invocation
	 * @return the invocation result, if any
	 * @throws Throwable in case of invocation failure
	 * @see #getPortStub()
	 * @see #doInvoke(org.aopalliance.intercept.MethodInvocation, Object)
	 */
protected Object doInvoke(MethodInvocation invocation) throws Throwable {
    try {
        return doInvoke(invocation, getPortStub());
    } catch (SOAPFaultException ex) {
        throw new JaxWsSoapFaultException(ex);
    } catch (ProtocolException ex) {
        throw new RemoteConnectFailureException("Could not connect to remote service [" + this.portQName + "]", ex);
    } catch (WebServiceException ex) {
        throw new RemoteAccessException("Could not access remote service at [" + this.portQName + "]", ex);
    }
}
Example 50
Project: spring-framework-master  File: JaxWsPortClientInterceptor.java View source code
/**
	 * Perform a JAX-WS service invocation based on the given method invocation.
	 * @param invocation the AOP method invocation
	 * @return the invocation result, if any
	 * @throws Throwable in case of invocation failure
	 * @see #getPortStub()
	 * @see #doInvoke(org.aopalliance.intercept.MethodInvocation, Object)
	 */
protected Object doInvoke(MethodInvocation invocation) throws Throwable {
    try {
        return doInvoke(invocation, getPortStub());
    } catch (SOAPFaultException ex) {
        throw new JaxWsSoapFaultException(ex);
    } catch (ProtocolException ex) {
        throw new RemoteConnectFailureException("Could not connect to remote service [" + getEndpointAddress() + "]", ex);
    } catch (WebServiceException ex) {
        throw new RemoteAccessException("Could not access remote service at [" + getEndpointAddress() + "]", ex);
    }
}
Example 51
Project: teiid-designer-master  File: TeiidWSProvider.java View source code
public Source execute(String procedureName, String inputMessage, String wsdlOperation, Properties properties) throws SOAPFaultException, SOAPException {
    Connection conn = null;
    PreparedStatement statement = null;
    ResultSet set = null;
    // Get a connection
    Source returnFragment = null;
    try {
        DataSource ds = getDataSource(properties);
        conn = ds.getConnection();
        String responseString;
        boolean noParm = false;
        if (//$NON-NLS-1$
        inputMessage.equals("")) {
            noParm = true;
        }
        //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
        final String executeStatement = "call " + procedureName + (noParm ? "()" : "(?)") + ";";
        statement = conn.prepareStatement(executeStatement);
        if (!noParm) {
            statement.setString(1, inputMessage);
        }
        final boolean hasResultSet = statement.execute();
        if (hasResultSet) {
            set = statement.getResultSet();
            if (set.next()) {
                /*
					 * an XML result set that is appropriate for a Data Service
					 * web service will ALWAYS return a single XML Document
					 * result. The first row in the first column. If there are
					 * additional rows, we throw an exception as this resultset
					 * is not appropriate for a Data Service.
					 */
                SQLXML sqlXml = (SQLXML) set.getObject(1);
                responseString = ((SQLXML) sqlXml).getString();
                InputStream is = null;
                try {
                    is = new ByteArrayInputStream(responseString.getBytes(//$NON-NLS-1$
                    "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    logger.log(Level.SEVERE, SoapPlugin.Util.getString("TeiidWSProvider.1") + procedureName);
                    createSOAPFaultMessage(e, e.getMessage(), SOAP_11_STANDARD_SERVER_FAULT_CODE);
                }
                returnFragment = new StreamSource(is);
            } else {
                logger.log(Level.WARNING, SoapPlugin.Util.getString(//$NON-NLS-1$
                "TeiidWSProvider.8") + procedureName);
                createSOAPFaultMessage(new Exception(SoapPlugin.Util.getString(//$NON-NLS-1$
                "TeiidWSProvider.2")), //$NON-NLS-1$
                SoapPlugin.Util.getString(//$NON-NLS-1$
                "TeiidWSProvider.3"), SOAP_11_STANDARD_SERVER_FAULT_CODE);
            }
            if (set.next()) {
                createSOAPFaultMessage(new Exception(SoapPlugin.Util.getString(//$NON-NLS-1$
                "TeiidWSProvider.4") + wsdlOperation + //$NON-NLS-1$
                SoapPlugin.Util.getString(//$NON-NLS-1$
                "TeiidWSProvider.5")), //$NON-NLS-1$
                SoapPlugin.Util.getString(//$NON-NLS-1$
                "TeiidWSProvider.6"), SOAP_11_STANDARD_SERVER_FAULT_CODE);
            }
            set.close();
        }
        statement.close();
    /*
			 * If we fall through to here and no XML Fragment has been set on
			 * the returnMessage instance because 'hasResults' was false, then
			 * the return message is an empty message with no body contents. We
			 * do this only because we do not know what to do with a returned
			 * update count. We cannot return it as the body of the message
			 * because we will likely violate the schema type that defines the
			 * return message. The only thing i can think to do is to return an
			 * empty message in this instance. We really should handle this
			 * situation more explicitly in the future. (ie Operations in Web
			 * Service Models in the modeler should be able to be considered
			 * 'update' type operations and return a simple int).
			 */
    } catch (SQLException e) {
        String faultcode = SOAP_11_STANDARD_SERVER_FAULT_CODE;
        String msg = SoapPlugin.Util.getString("TeiidWSProvider.1");
        logger.logrb(Level.SEVERE, "TeiidWSProvider", "execute", SoapPlugin.PLUGIN_ID, msg, new Throwable(e));
        if (e instanceof SQLException) {
            final SQLException sqlException = (SQLException) e;
            if (SQLStates.isUsageErrorState(sqlException.getSQLState())) {
                faultcode = SOAP_11_STANDARD_CLIENT_FAULT_CODE;
            }
        }
        createSOAPFaultMessage(e, e.getMessage(), faultcode);
    } catch (Exception e) {
        String faultcode = SOAP_11_STANDARD_SERVER_FAULT_CODE;
        String msg = SoapPlugin.Util.getString("TeiidWSProvider.1");
        logger.logrb(Level.SEVERE, "TeiidWSProvider", "execute", SoapPlugin.PLUGIN_ID, msg, new Throwable(e));
        if (e instanceof SQLException) {
            final SQLException sqlException = (SQLException) e;
            if (SQLStates.isUsageErrorState(sqlException.getSQLState())) {
                faultcode = SOAP_11_STANDARD_CLIENT_FAULT_CODE;
            }
        }
        createSOAPFaultMessage(e, e.getMessage(), faultcode);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                String msg = SoapPlugin.Util.getString("TeiidWSProvider.1");
                logger.logrb(Level.SEVERE, "TeiidWSProvider", "execute", SoapPlugin.PLUGIN_ID, msg, new Throwable(e));
            }
        }
    }
    return returnFragment;
}
Example 52
Project: resin-master  File: AbstractAction.java View source code
protected Throwable readFault(XMLStreamReader in) throws IOException, XMLStreamException, JAXBException, SOAPException {
    Throwable fault = null;
    String message = null;
    String actor = null;
    SOAPFault soapFault = createSOAPFault();
    while (in.nextTag() == XMLStreamReader.START_ELEMENT) {
        if ("faultcode".equals(in.getLocalName())) {
            if (in.next() == XMLStreamReader.CHARACTERS) {
                String code = in.getText();
                int colon = code.indexOf(':');
                if (colon >= 0)
                    code = code.substring(colon + 1);
                if ("Server".equalsIgnoreCase(code)) {
                // XXX Do anything with this?
                } else if ("Client".equalsIgnoreCase(code)) {
                // XXX Do anything with this?
                } else if ("VersionMismatch".equalsIgnoreCase(code)) {
                // XXX Do anything with this?
                } else if ("MustUnderstand".equalsIgnoreCase(code)) {
                // XXX Do anything with this?
                }
                soapFault.setFaultCode(code);
            }
            while (in.nextTag() != XMLStreamReader.END_ELEMENT) {
            }
        } else if ("faultstring".equals(in.getLocalName())) {
            if (in.next() == XMLStreamReader.CHARACTERS)
                message = in.getText();
            soapFault.setFaultString(message);
            while (in.nextTag() != XMLStreamReader.END_ELEMENT) {
            }
        } else if ("faultactor".equals(in.getLocalName())) {
            if (in.next() == XMLStreamReader.CHARACTERS)
                actor = in.getText();
            soapFault.setFaultActor(actor);
            while (in.nextTag() != XMLStreamReader.END_ELEMENT) {
            }
        } else if ("detail".equals(in.getLocalName())) {
            if (in.nextTag() == XMLStreamReader.START_ELEMENT) {
                ParameterMarshal faultMarshal = _faultNames.get(in.getName());
                if (faultMarshal != null)
                    fault = (Exception) faultMarshal.deserializeReply(in, fault);
            }
        }
    }
    if (fault == null)
        fault = new SOAPFaultException(soapFault);
    return fault;
}
Example 53
Project: tuscany-sca-2.x-master  File: JAXWSBindingInvoker.java View source code
public Message invoke(Message msg) {
    try {
        SOAPMessage resp = invokeTarget(msg);
        SOAPBody body = resp.getSOAPBody();
        if (body != null) {
            SOAPFault fault = body.getFault();
            if (fault != null) {
            // setFault(msg, fault);
            } else {
                // The 1st child element
                msg.setBody(body.getChildElements().next());
            }
        }
    } catch (SOAPFaultException e) {
        setFault(msg, e);
    } catch (WebServiceException e) {
        msg.setFaultBody(e);
    } catch (SOAPException e) {
        msg.setFaultBody(e);
    } catch (Throwable e) {
        msg.setFaultBody(e);
    }
    return msg;
}
Example 54
Project: vhm-master  File: VCConnection.java View source code
public void disconnect(boolean testAsyncDrop) throws SOAPFaultException {
    if (_connected) {
        try {
            getVimPort().logout(getServiceContent().getSessionManager());
            if (!testAsyncDrop) {
                // for testing connection drop asynchronous to VHM operation.
                _connected = false;
            }
        } catch (RuntimeFaultFaultMsg e) {
            throw new RuntimeException("Unexpected Disconnect Exception", e);
        }
    }
}
Example 55
Project: cloudstack-master  File: VmwareContext.java View source code
public void close() {
    clearStockObjects();
    try {
        s_logger.info("Disconnecting VMware session");
        _vimClient.disconnect();
    } catch (SOAPFaultException sfe) {
        s_logger.debug("Tried to disconnect a session that is no longer valid");
    } catch (Exception e) {
        s_logger.warn("Unexpected exception: ", e);
    } finally {
        if (_pool != null) {
            _pool.unregisterContext(this);
        }
        unregisterOutstandingContext();
    }
}
Example 56
Project: muCommander-master  File: VSphereFile.java View source code
private void checkAttributues(VsphereConnHandler connHandler) throws IOException, FileFaultFaultMsg, GuestOperationsFaultFaultMsg, InvalidStateFaultMsg, RuntimeFaultFaultMsg, TaskInProgressFaultMsg, InvalidPropertyFaultMsg {
    ManagedObjectReference fileManager = getFileManager(connHandler);
    GuestListFileInfo res = null;
    try {
        res = connHandler.getClient().getVimPort().listFilesInGuest(fileManager, vm, credentials, getPathInVm(), null, null, null);
    } catch (SOAPFaultException e) {
        if (isFileNotFound(e)) {
            return;
        }
        throw e;
    }
    if (res.getFiles().size() == 1) {
        // only one result - it's a file
        GuestFileInfo guestFileInfo = res.getFiles().get(0);
        updateAttributes(guestFileInfo);
    } else {
        // find the entry for "."
        for (GuestFileInfo f : res.getFiles()) {
            if (f.getPath().equals(".")) {
                updateAttributes(f);
                break;
            }
        }
    }
}
Example 57
Project: EasySOA-master  File: SimpleProvider.java View source code
@javax.jws.WebMethod(operationName = "getAirportInformationByISOCountryCode", action = "http://airportsoap.sopera.de/getAirportInformationByISOCountryCode")
@javax.jws.WebResult(name = "getAirportInformationByISOCountryCodeOutput", targetNamespace = "http://airportsoap.sopera.de", partName = "response")
public javax.xml.transform.Source invoke(@javax.jws.WebParam(name = "getAirportInformationByISOCountryCodeInput", targetNamespace = "http://airportsoap.sopera.de", partName = "request") javax.xml.transform.Source request) {
    try {
        org.dom4j.io.DocumentResult docResult = new org.dom4j.io.DocumentResult();
        factory.newTransformer().transform(request, docResult);
        org.dom4j.Document requestDoc = docResult.getDocument();
        // System.out.println("request: " +
        // requestDoc.asXML());
        QueuedExchangeContextImpl<org.dom4j.Document> messageExchange = messageHandler.invoke(requestDoc);
        try {
            if (messageExchange.isFault()) {
                throw messageExchange.getFault();
            // String faultString =
            // messageExchange.getFaultMessage();
            // // System.out.println("fault: " +
            // faultString);
            //
            // if (messageExchange.isBusinessFault()) {
            // org.dom4j.Document faultDoc =
            // messageExchange.getBusinessFaultDetails();
            // javax.xml.soap.SOAPFactory soapFactory =
            // javax.xml.soap.SOAPFactory.newInstance();
            // javax.xml.soap.SOAPFault soapFault =
            // soapFactory.createFault(faultString,
            // new javax.xml.namespace.QName(TNS,
            // "businessFault"));
            // if (null != faultDoc) {
            // //
            // System.out.println("business fault details: "
            // + faultDoc.asXML());
            // org.dom4j.io.DOMWriter writer = new
            // org.dom4j.io.DOMWriter();
            // org.w3c.dom.Document faultDetailDom =
            // writer.write(faultDoc);
            // soapFault.addDetail().appendChild(
            // soapFault.getOwnerDocument().importNode(
            // faultDetailDom.getDocumentElement(),
            // true));
            // }
            // throw new
            // javax.xml.ws.soap.SOAPFaultException(soapFault);
            // } else {
            // Throwable error =
            // messageExchange.getFault();
            // // System.out.println("job error: " +
            // error.getMessage());
            // if (error instanceof RuntimeException) {
            // throw (RuntimeException) error;
            // } else {
            // throw new RuntimeException(faultString,
            // error);
            // }
            // }
            } else {
                org.dom4j.Document responseDoc = messageExchange.getResponse();
                if (null == responseDoc) {
                    // System.out.println("response: empty");
                    throw new RuntimeException("no response provided by Talend job");
                }
                return new org.dom4j.io.DocumentSource(responseDoc);
            }
        } finally {
            messageExchange.completeQueuedProcessing();
        }
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Throwable ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
    // System.out.println(System.currentTimeMillis() +
    // " <- handleMessage");
    }
}
Example 58
Project: openolat-master  File: ViteroManager.java View source code
public List<ViteroBooking> getBookingByDate(Date start, Date end) throws VmsNotAvailableException {
    try {
        Booking bookingWs = getBookingWebService();
        GetBookingListByDateRequest dateRequest = new GetBookingListByDateRequest();
        dateRequest.setStart(format(start));
        dateRequest.setEnd(format(end));
        dateRequest.setTimezone(viteroModule.getTimeZoneId());
        dateRequest.setCustomerid(viteroModule.getCustomerId());
        Bookinglist bookingList = bookingWs.getBookingListByDate(dateRequest);
        List<Booking_Type> bookings = bookingList.getBooking();
        return convert(bookings);
    } catch (SOAPFaultException f) {
        ErrorCode code = handleAxisFault(f);
        switch(code) {
            default:
                logAxisError("Cannot get the list of bookings by date.", f);
        }
        return Collections.emptyList();
    } catch (WebServiceException e) {
        if (e.getCause() instanceof ConnectException) {
            throw new VmsNotAvailableException();
        }
        return Collections.emptyList();
    }
}
Example 59
Project: springlab-master  File: SecurityWebServiceTest.java View source code
/**
	 * 测试访问没有与SpringSecurity结�的EndPoint, 调用�SpringSecurity�护的方法, 用<jaxws:client/>创建的Client.
	 */
@Test(expected = SOAPFaultException.class)
public void getUserWithSpringSecurityWithoutPermission() {
    UserWebService userWebService = (UserWebService) applicationContext.getBean("userServiceWithPlainPassword");
    GetUserResult result = userWebService.getUser("1");
    assertEquals("admin", result.getUser().getLoginName());
}
Example 60
Project: smock-master  File: CalcSimpleTest.java View source code
@Test(expected = SOAPFaultException.class)
public void testException() throws IOException {
    expect(validPayload(resource("xsd/calc.xsd"))).andExpect(message("request-ignore.xml")).andRespond(withMessage("fault.xml"));
    calc.plus(2, 3);
}