Java 类javax.xml.soap.MessageFactory 实例源码

项目:openjdk-jdk10    文件:XmlTest.java   
public void test() throws Exception {

        File file = new File("message.xml");
        file.deleteOnExit();

        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage msg = createMessage(mf);

        // Save the soap message to file
        try (FileOutputStream sentFile = new FileOutputStream(file)) {
            msg.writeTo(sentFile);
        }

        // See if we get the image object back
        try (FileInputStream fin = new FileInputStream(file)) {
            SOAPMessage newMsg = mf.createMessage(msg.getMimeHeaders(), fin);

            newMsg.writeTo(new ByteArrayOutputStream());

            Iterator<?> i = newMsg.getAttachments();
            while (i.hasNext()) {
                AttachmentPart att = (AttachmentPart) i.next();
                Object obj = att.getContent();
                if (!(obj instanceof StreamSource)) {
                    fail("Got incorrect attachment type [" + obj.getClass() + "], " +
                         "expected [javax.xml.transform.stream.StreamSource]");
                }
            }
        }

    }
项目:openjdk-jdk10    文件:XmlTest.java   
private SOAPMessage createMessage(MessageFactory mf) throws SOAPException, IOException {
    SOAPMessage msg = mf.createMessage();
    SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
    Name name = envelope.createName("hello", "ex", "http://example.com");
    envelope.getBody().addChildElement(name).addTextNode("THERE!");

    String s = "<root><hello>THERE!</hello></root>";

    AttachmentPart ap = msg.createAttachmentPart(
            new StreamSource(new ByteArrayInputStream(s.getBytes())),
            "text/xml"
    );
    msg.addAttachmentPart(ap);
    msg.saveChanges();

    return msg;
}
项目:jbossws-cxf    文件:CalendarTestCase.java   
@Test
@RunAsClient
public void testEmptyCalendar() throws Exception {
   URL wsdlURL = new URL(baseURL + "/EndpointService?wsdl");
   QName qname = new QName("http://org.jboss.ws/jaxws/calendar", "EndpointService");
   Service service = Service.create(wsdlURL, qname);

   Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName("http://org.jboss.ws/jaxws/calendar", "EndpointPort"), SOAPMessage.class, Mode.MESSAGE);

   String reqEnv = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns2:echoCalendar xmlns:ns2=\"http://org.jboss.ws/jaxws/calendar\"><arg0/></ns2:echoCalendar></soap:Body></soap:Envelope>";

   SOAPMessage reqMsg = MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(reqEnv.getBytes()));
   SOAPMessage resMsg = dispatch.invoke(reqMsg);

   assertNotNull(resMsg);
   //TODO improve checks
}
项目:OpenJSharp    文件:SAAJMetaFactoryImpl.java   
protected  MessageFactory newMessageFactory(String protocol)
    throws SOAPException {
    if (SOAPConstants.SOAP_1_1_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl();
    } else if (SOAPConstants.SOAP_1_2_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.ver1_2.SOAPMessageFactory1_2Impl();
    } else if (SOAPConstants.DYNAMIC_SOAP_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.dynamic.SOAPMessageFactoryDynamicImpl();
    } else {
        log.log(
            Level.SEVERE,
            "SAAJ0569.soap.unknown.protocol",
            new Object[] {protocol, "MessageFactory"});
        throw new SOAPException("Unknown Protocol: " + protocol +
                                    "  specified for creating MessageFactory");
    }
}
项目:xrd4j    文件:AbstractServiceRequestSerializer.java   
/**
 * Serializes the given ServiceRequest to SOAPMessage.
 *
 * @param request ServiceRequest to be serialized
 * @return SOAPMessage representing the given ServiceRequest; null if the
 * operation fails
 */
@Override
public final SOAPMessage serialize(final ServiceRequest request) {
    try {
        LOGGER.debug("Serialize ServiceRequest message to SOAP.");
        MessageFactory myMsgFct = MessageFactory.newInstance();
        SOAPMessage message = myMsgFct.createMessage();

        request.setSoapMessage(message);

        // Generate header
        super.serializeHeader(request, message.getSOAPPart().getEnvelope());

        // Generate body
        this.serializeBody(request);

        LOGGER.debug("ServiceRequest message was serialized succesfully.");
        return message;
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    LOGGER.warn("Failed to serialize ServiceRequest message to SOAP.");
    return null;
}
项目:openjdk-jdk10    文件:SAAJMetaFactoryImpl.java   
@Override
protected  MessageFactory newMessageFactory(String protocol)
    throws SOAPException {
    if (SOAPConstants.SOAP_1_1_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl();
    } else if (SOAPConstants.SOAP_1_2_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.ver1_2.SOAPMessageFactory1_2Impl();
    } else if (SOAPConstants.DYNAMIC_SOAP_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.dynamic.SOAPMessageFactoryDynamicImpl();
    } else {
        log.log(
            Level.SEVERE,
            "SAAJ0569.soap.unknown.protocol",
            new Object[] {protocol, "MessageFactory"});
        throw new SOAPException("Unknown Protocol: " + protocol +
                                    "  specified for creating MessageFactory");
    }
}
项目:openjdk9    文件:XmlTest.java   
private SOAPMessage createMessage(MessageFactory mf) throws SOAPException, IOException {
    SOAPMessage msg = mf.createMessage();
    SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
    Name name = envelope.createName("hello", "ex", "http://example.com");
    envelope.getBody().addChildElement(name).addTextNode("THERE!");

    String s = "<root><hello>THERE!</hello></root>";

    AttachmentPart ap = msg.createAttachmentPart(
            new StreamSource(new ByteArrayInputStream(s.getBytes())),
            "text/xml"
    );
    msg.addAttachmentPart(ap);
    msg.saveChanges();

    return msg;
}
项目:openjdk9    文件:SAAJMetaFactoryImpl.java   
protected  MessageFactory newMessageFactory(String protocol)
    throws SOAPException {
    if (SOAPConstants.SOAP_1_1_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl();
    } else if (SOAPConstants.SOAP_1_2_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.ver1_2.SOAPMessageFactory1_2Impl();
    } else if (SOAPConstants.DYNAMIC_SOAP_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.dynamic.SOAPMessageFactoryDynamicImpl();
    } else {
        log.log(
            Level.SEVERE,
            "SAAJ0569.soap.unknown.protocol",
            new Object[] {protocol, "MessageFactory"});
        throw new SOAPException("Unknown Protocol: " + protocol +
                                    "  specified for creating MessageFactory");
    }
}
项目:atf-toolbox-java    文件:WebServiceAutomationManager.java   
/**
 * createSOAPRequestMessage - create a SOAP message from an object
 *
 * @param webServiceKey
 *            key to locate the web service
 * @param request
 *            - request body content
 * @param action
 *            - SOAP Action string
 * @return SOAPMessage
 * @throws SOAPException
 *             - if there was an error creating the SOAP Connection
 * @throws JAXBException
 *             - if there was an error marshalling the SOAP Message
 */
private SOAPMessage createSOAPRequestMessage(String webServiceKey, Object request, String action) throws SOAPException, JAXBException {
    WebService service = getWebService(webServiceKey);

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", service.getNamespaceURI());

    if (action != null) {
        MimeHeaders headers = message.getMimeHeaders();
        headers.addHeader("SOAPAction", service.getNamespaceURI() + "VerifyEmail");
    }

    // SOAP Body
    SOAPBody body = message.getSOAPBody();

    marshallObject(webServiceKey, request, body);

    message.saveChanges();
    return message;
}
项目:OSCAR-ConCert    文件:OSCARFAXSOAPMessage.java   
public OSCARFAXSOAPMessage(MessageFactory mf)
    throws SOAPException
{
    this.mf = mf;
    msg = mf.createMessage();
    soapPart = msg.getSOAPPart();
    envelope = soapPart.getEnvelope();
    SOAPBody body = envelope.getBody();
    SOAPElement ele = body.addChildElement(envelope.createName("OscarFax", "jaxm", "http://oscarhome.org/jaxm/oscarFax/"));
    sendingProvider = ele.addChildElement("sendingProvider");
    locationId = ele.addChildElement("locationId");
    identifier = ele.addChildElement("identifier");
    faxType = ele.addChildElement("faxType");
    coverSheet = ele.addChildElement("coverSheet");
    from = ele.addChildElement("from");
    comments = ele.addChildElement("comments");
    sendersFax = ele.addChildElement("sendersFax");
    sendersPhone = ele.addChildElement("sendersPhone");
    dateOfSending = ele.addChildElement("dateOfSending");
    recipient = ele.addChildElement("recipient");
    recipientFaxNumber = ele.addChildElement("recipientFaxNumber");
    payLoad = ele.addChildElement(envelope.createName("OscarFaxPayLoad", "jaxm", "http://oscarhome.org/jaxm/oscarFax/"));
}
项目:soap-wrapper-lambda    文件:ExampleSoapMessage.java   
public static SOAPMessage create() throws SOAPException {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage message = messageFactory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();

    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("codecentric", "https://www.codecentric.de");

    SOAPBody envelopeBody = envelope.getBody();
    SOAPElement soapBodyElem = envelopeBody.addChildElement("location", "codecentric");

    SOAPElement place = soapBodyElem.addChildElement("place", "codecentric");
    place.addTextNode("Berlin");

    MimeHeaders headers = message.getMimeHeaders();
    headers.addHeader("SOAPAction", "https://www.codecentric.de/location");

    message.saveChanges();
    return message;
}
项目:irsclient    文件:ManifestProcessor.java   
public ACATransmitterManifestReqDtl getObject(File file) {
    ACATransmitterManifestReqDtl dtl = null;
    try {
        String fileContents = FileUtils.readFileToString(file, "UTF-8");
        SOAPMessage message = MessageFactory.newInstance().createMessage(null,
                new ByteArrayInputStream(fileContents.getBytes()));
        Unmarshaller unmarshaller = JAXBContext.newInstance(ACATransmitterManifestReqDtl.class)
                .createUnmarshaller();

        Iterator iterator = message.getSOAPHeader().examineAllHeaderElements();
        while (iterator.hasNext()) {
            SOAPHeaderElement element = (SOAPHeaderElement) iterator.next();
            QName name = new QName("urn:us:gov:treasury:irs:ext:aca:air:7.0", "ACATransmitterManifestReqDtl",
                    "urn");
            if (element.getElementQName().equals(name)) {
                dtl = (ACATransmitterManifestReqDtl) unmarshaller.unmarshal(processElement(element));
            }

        }
    } catch (Exception e) {
        LOG.error("Error", e);
    }
    return dtl;

}
项目:lookaside_java-1.8.0-openjdk    文件:SAAJMetaFactoryImpl.java   
protected  MessageFactory newMessageFactory(String protocol)
    throws SOAPException {
    if (SOAPConstants.SOAP_1_1_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl();
    } else if (SOAPConstants.SOAP_1_2_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.ver1_2.SOAPMessageFactory1_2Impl();
    } else if (SOAPConstants.DYNAMIC_SOAP_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.dynamic.SOAPMessageFactoryDynamicImpl();
    } else {
        log.log(
            Level.SEVERE,
            "SAAJ0569.soap.unknown.protocol",
            new Object[] {protocol, "MessageFactory"});
        throw new SOAPException("Unknown Protocol: " + protocol +
                                    "  specified for creating MessageFactory");
    }
}
项目:libreacs    文件:MessageTest.java   
private void messageTest(String m) throws SOAPException, IOException {
    MessageFactory mf;
    mf = MessageFactory.newInstance();

    ByteArrayInputStream f = new ByteArrayInputStream(m.getBytes());

    SOAPMessage soapMsg = mf.createMessage(null, f);

    Message msg = null;
    try {
        msg = Message.Parse(soapMsg);
    } catch (Exception ex) {
        ex.printStackTrace();
        return;
    }

}
项目:Open-Clinica-Data-Uploader    文件:AuthenticationTests.java   
@Before
public void setUp() throws Exception {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    this.authFailPureXML = docBuilder.parse(new File("docs/responseExamples/auth_error.xml"));
    MessageFactory messageFactory = MessageFactory.newInstance();
    File authSuccess = new File("docs/responseExamples/listStudiesResponse.xml"); //TODO: Replace File with Path
    File authFailure = new File("docs/responseExamples/auth_error.xml"); //TODO: Replace File with Path

    FileInputStream inSuccess = new FileInputStream(authSuccess);
    FileInputStream inFail = new FileInputStream(authFailure);

    this.testDocumentAuthSuccess = SoapUtils.toDocument(messageFactory.createMessage(null, inSuccess));
    this.testDocumentAuthFail = SoapUtils.toDocument(messageFactory.createMessage(null, inFail));
    inSuccess.close();
    inFail.close();
}
项目:Open-Clinica-Data-Uploader    文件:ClinicalDataOcChecksTests.java   
@Test
    public void eventStatusCheck() throws Exception {
        File testFile = new File("docs/responseExamples/getStudyMetadata3.xml");
        FileInputStream in = new FileInputStream(testFile);
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage mockedResponseGetMetadata = messageFactory.createMessage(null, in);//soapMessage;
        MetaData crfVersionMetaData = GetStudyMetadataResponseHandler.parseGetStudyMetadataResponse(mockedResponseGetMetadata);
        List<StudySubjectWithEventsType> incorrectEventStatus = incorrectEventStatusExample();
        List<ClinicalData> incorrectData = new ArrayList<>();
        ClinicalData dPoint = new ClinicalData("Eventful", "age", "ssid1",
                "RepeatingEvent", 1, "MUST-FOR_NON_TTP_STUDY", null, "0.08", null, null, "12");
        incorrectData.add(dPoint);
        clinicalDataOcChecks = new ClinicalDataOcChecks(crfVersionMetaData, incorrectData, incorrectEventStatus);
        in.close();
        List<ValidationErrorMessage> errors = clinicalDataOcChecks.getErrors();
        assertThat(errors, hasSize(1));
        assertThat(errors, hasItem(isA(EventStatusNotAllowed.class)));
//        assertThat(errors, hasItem(isA(MandatoryItemInCrfMissing.class)));
    }
项目:Open-Clinica-Data-Uploader    文件:PatientDataFactoryTests.java   
@Before
public void setUp() throws Exception {
    String username = "tester";
    this.user = new OcUser();
    this.user.setUsername(username);
    this.uploadSession = new UploadSession("testSubmission", UploadSession.Step.MAPPING, new Date(), this.user);
    this.factory = new PatientDataFactory(user, uploadSession);
    try {
        MessageFactory messageFactory = MessageFactory.newInstance();
        FileInputStream in = new FileInputStream(new File("docs/responseExamples/Sjogren_STUDY1.xml"));

        SOAPMessage mockedResponseGetMetadata = messageFactory.createMessage(null, in);
        this.metadata = GetStudyMetadataResponseHandler.parseGetStudyMetadataResponse(mockedResponseGetMetadata);
    } catch (Exception e) {
        e.printStackTrace();
    }
    this.subjectMap = new HashMap<>();
    this.subjectMap.put("test_ssid_1", null);
}
项目:Open-Clinica-Data-Uploader    文件:EventDataFactoryTests.java   
@Before
public void setUp() throws Exception {
    this.testUser = new OcUser();
    this.testUser.setUsername("tester");
    this.testSubmission = new UploadSession("submission1", UploadSession.Step.MAPPING, new Date(), this.testUser);
    this.factory = new EventDataFactory(testUser, testSubmission);
    try {
        MessageFactory messageFactory = MessageFactory.newInstance();
        FileInputStream in = new FileInputStream(new File("docs/responseExamples/getStudyMetadata3.xml"));

        SOAPMessage mockedResponseGetMetadata = messageFactory.createMessage(null, in);
        this.metadata = GetStudyMetadataResponseHandler.parseGetStudyMetadataResponse(mockedResponseGetMetadata);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Open-Clinica-Data-Uploader    文件:ODMGenerationTests.java   
@Before
public void setUp() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    File testFile = new File("docs/responseExamples/getStudyMetadata3.xml");
    FileInputStream in = new FileInputStream(testFile);
    SOAPMessage mockedResponseGetMetadata = messageFactory.createMessage(null, in);//soapMessage;
    this.metaData = GetStudyMetadataResponseHandler.parseGetStudyMetadataResponse(mockedResponseGetMetadata);

    this.testUser = new OcUser();
    this.testUser.setUsername("tester");
    this.testSubmission = new UploadSession("submission1", UploadSession.Step.MAPPING, new Date(), this.testUser);
    this.factory = new ClinicalDataFactory(testUser, testSubmission);

    this.testSubjectWithEventsTypeList = TestUtils.createStudySubjectWithEventList();

    this.uploadSession = new UploadSession("submission1", UploadSession.Step.MAPPING, new Date(), this.testUser);

    this.testODMGenerationCorrect = Paths.get("docs/exampleFiles/odmGeneration.txt");
}
项目:Camel    文件:TesterBean.java   
public static SOAPMessage createDefaultSoapMessage(String responseMessage, String requestMessage) {
    try {
        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();

        QName payloadName = new QName("http://apache.org/hello_world_soap_http/types", "greetMeResponse", "ns1");

        SOAPBodyElement payload = body.addBodyElement(payloadName);

        SOAPElement message = payload.addChildElement("responseType");

        message.addTextNode(responseMessage + " Request was  " + requestMessage);
        return soapMessage;
    } catch (SOAPException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
项目:Camel    文件:SoapToSoapDontIgnoreTest.java   
@Test
public void testSoapMarshal() throws Exception {
    MockEndpoint endpoint = getMockEndpoint("mock:end");
    endpoint.setExpectedMessageCount(1);

    template.sendBody("direct:start", createRequest());

    assertMockEndpointsSatisfied();
    Exchange result = endpoint.assertExchangeReceived(0);

    byte[] body = (byte[])result.getIn().getBody();
    InputStream stream = new ByteArrayInputStream(body);
    SOAPMessage request = MessageFactory.newInstance().createMessage(null, stream);
    assertTrue("Expected headers", null != request.getSOAPHeader()
                                   && request.getSOAPHeader().extractAllHeaderElements().hasNext());
}
项目:Camel    文件:SoapToSoapSingleDataFormatterTest.java   
@Test
public void testSoapMarshal() throws Exception {
    MockEndpoint endpoint = getMockEndpoint("mock:end");
    endpoint.setExpectedMessageCount(1);

    template.sendBody("direct:start", createRequest());

    assertMockEndpointsSatisfied();
    Exchange result = endpoint.assertExchangeReceived(0);

    byte[] body = (byte[])result.getIn().getBody();
    InputStream stream = new ByteArrayInputStream(body);
    SOAPMessage request = MessageFactory.newInstance().createMessage(null, stream);
    assertTrue("Expected headers", null != request.getSOAPHeader()
                                   && request.getSOAPHeader().extractAllHeaderElements().hasNext());
}
项目:Camel    文件:SoapToSoapIgnoreTest.java   
@Test
public void testSoapMarshal() throws Exception {
    MockEndpoint endpoint = getMockEndpoint("mock:end");
    endpoint.setExpectedMessageCount(1);

    template.sendBody("direct:start", createRequest());

    assertMockEndpointsSatisfied();
    Exchange result = endpoint.assertExchangeReceived(0);

    byte[] body = (byte[])result.getIn().getBody();
    InputStream stream = new ByteArrayInputStream(body);
    SOAPMessage request = MessageFactory.newInstance().createMessage(null, stream);
    assertTrue("Expected no headers", null == request.getSOAPHeader()
                                      || !request.getSOAPHeader().extractAllHeaderElements().hasNext());
}
项目:java-ws-discovery    文件:SOAPOverUDPMessage.java   
public SOAPOverUDPMessage(String soapAsXML, String soapProtocol, Charset encoding) throws SOAPOverUDPException {
    MessageFactory factory;
    SOAPMessage message = null;
    try {
        factory = MessageFactory.newInstance(soapProtocol);
        message = factory.createMessage();                     
        if (soapAsXML != null) {
            ByteArrayInputStream i = new ByteArrayInputStream(soapAsXML.getBytes(encoding));
            message.getSOAPPart().setContent(new StreamSource(i));
            this.soapMessage = message;
            this.readWSAHeader(); // read header
        } else
            this.soapMessage = message;
    } catch (SOAPException ex) {
        throw new SOAPOverUDPException("Unable to create SOAP message.");
    }
}
项目:AJ    文件:SoapUtil.java   
/**
 * Creates a {@link SOAPMessage} object from the specified byte array.
 *
 * @param content     the raw message to parse the <code>SOAPMessage</code> from
 * @param contentType the HTTP Content-Type value that corresponds to the message. Required in order to determine if
 *                    the message should be parsed as a standard XML message or a multipart message with attachments.
 * @return the SOAPMessage object parsed from the given byte array
 * @throws SOAPException if the message is not a valid SOAP message
 */
public static SOAPMessage parseMessage(byte[] content, String contentType) throws SOAPException {
  ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
  try {
    MessageFactory messageFactory = MessageFactory.newInstance();
    MimeHeaders headers = new MimeHeaders();
    headers.addHeader(HttpUtil.HEADER_CONTENT_TYPE, contentType);
    return messageFactory.createMessage(headers, inputStream);
  } catch (IOException e) {
    /* Should never happen - ByteArrayInputStream in this case is always readable and if its contents are invalid,
     * SOAPException will be thrown instead. */
    throw ExceptionUtil.toUnchecked(e);
  } finally {
    IOUtil.close(inputStream);
  }
}
项目:jbossws-cxf    文件:JBWS3084CxfTestCase.java   
@Test
@RunAsClient
public void testSoapConnectionGet() throws Exception
{
   final String serviceURL = baseURL + "/greetMe";
   SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance();

   SOAPConnection con = conFac.createConnection();
   URL endpoint = new URL(serviceURL);
   MessageFactory msgFactory = MessageFactory.newInstance();
   SOAPMessage msg = msgFactory.createMessage();
   msg.getSOAPBody().addBodyElement(new QName("http://www.jboss.org/jbossws/saaj", "greetMe"));
   SOAPMessage response = con.call(msg, endpoint);
   QName greetMeResp = new QName("http://www.jboss.org/jbossws/saaj", "greetMeResponse");

   Iterator<?> sayHiRespIterator = response.getSOAPBody().getChildElements(greetMeResp);
   SOAPElement soapElement = (SOAPElement) sayHiRespIterator.next();
   assertNotNull(soapElement);

   assertEquals(1, response.countAttachments());
}
项目:jbossws-cxf    文件:ClientSOAPHandler.java   
protected boolean handleOutbound(final SOAPMessageContext msgContext)
{
   try
   {
      SOAPFault fault = null;
      MessageFactory factory = MessageFactory.newInstance(); 
      SOAPMessage resMessage = factory.createMessage();
      fault = resMessage.getSOAPBody().addFault();
      fault.setFaultString("this is an exception thrown by client outbound");
      throw new SOAPFaultException(fault);
   }
   catch (SOAPException e)
   {
      //ignore
   }
   return true;
}
项目:jbossws-cxf    文件:JBWS3945TestCase.java   
@Test
@RunAsClient
public void testSOAP12SoapFaultExceptionOnHTTP400UsingSAAJ() throws Exception
{
   try
   {
      //<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"><soap:Body><ns2:throwSoapFaultException xmlns:ns2="http://server.exception.samples.jaxws.ws.test.jboss.org/"/></soap:Body></soap:Envelope>

      SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance();

      SOAPConnection con = conFac.createConnection();
      MessageFactory msgFactory = MessageFactory.newInstance();
      SOAPMessage msg = msgFactory.createMessage();
      msg.getSOAPBody().addBodyElement(new QName(targetNS, "throwSoapFaultException"));
      SOAPMessage response = con.call(msg, new URL(targetEndpoint + "Servlet"));
      Element el = (Element)response.getSOAPBody().getChildElements().next();
      assertEquals("Fault", el.getLocalName());
   }
   catch (Exception e)
   {
      fail(e);
   }
}
项目:jbossws-cxf    文件:ProviderMessageTestCase.java   
@Test
@RunAsClient
public void testProviderMessageNullResponse() throws Exception
{
   MessageFactory msgFactory = MessageFactory.newInstance();
   SOAPMessage reqMsg = msgFactory.createMessage(null, new ByteArrayInputStream(msgStringForNullResponse.getBytes()));

   URL epURL = baseURL;
   SOAPConnection con = SOAPConnectionFactory.newInstance().createConnection();
   SOAPMessage resMsg = con.call(reqMsg, epURL);
   if (resMsg != null)
   {
      SOAPPart soapPart = resMsg.getSOAPPart();
      //verify there's either nothing in the reply or at least the response body is empty
      if (soapPart != null && soapPart.getEnvelope() != null && soapPart.getEnvelope().getBody() != null)
      {
         SOAPBody soapBody = soapPart.getEnvelope().getBody();
         assertFalse(soapBody.getChildElements().hasNext());
      }
   }
}
项目:jbossws-cxf    文件:WebMethodTestCase.java   
@Test
@RunAsClient
public void testLegalMessageAccess() throws Exception
{
   MessageFactory msgFactory = MessageFactory.newInstance();
   SOAPConnection con = SOAPConnectionFactory.newInstance().createConnection();

   String reqEnv =
      "<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>" +
      " <env:Header/>" +
      " <env:Body>" +
      "  <ns1:echoString xmlns:ns1='" + targetNS + "'>" +
      "   <arg0>Hello</arg0>" +
      "  </ns1:echoString>" +
      " </env:Body>" +
      "</env:Envelope>";
   SOAPMessage reqMsg = msgFactory.createMessage(null, new ByteArrayInputStream(reqEnv.getBytes()));

   URL epURL = new URL(baseURL + "/TestService");
   SOAPMessage resMsg = con.call(reqMsg, epURL);

   QName qname = new QName(targetNS, "echoStringResponse");
   SOAPElement soapElement = (SOAPElement)resMsg.getSOAPBody().getChildElements(qname).next();
   soapElement = (SOAPElement)soapElement.getChildElements(new QName("return")).next();
   assertEquals("Hello", soapElement.getValue());
}
项目:jbossws-cxf    文件:WebMethodTestCase.java   
@Test
@RunAsClient
public void testIllegalMessageAccess() throws Exception
{
   MessageFactory msgFactory = MessageFactory.newInstance();
   SOAPConnection con = SOAPConnectionFactory.newInstance().createConnection();

   String reqEnv =
      "<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>" +
      " <env:Header/>" +
      " <env:Body>" +
      "  <ns1:noWebMethod xmlns:ns1='" + targetNS + "'>" +
      "   <String_1>Hello</String_1>" +
      "  </ns1:noWebMethod>" +
      " </env:Body>" +
      "</env:Envelope>";
   SOAPMessage reqMsg = msgFactory.createMessage(null, new ByteArrayInputStream(reqEnv.getBytes()));

   URL epURL = new URL(baseURL + "/TestService");
   SOAPMessage resMsg = con.call(reqMsg, epURL);
   SOAPFault soapFault = resMsg.getSOAPBody().getFault();
   assertNotNull("Expected SOAPFault", soapFault);

   String faultString = soapFault.getFaultString();
   assertTrue(faultString, faultString.indexOf("noWebMethod") > 0);
}
项目:jbossws-cxf    文件:MultipartContentTypeTestCase.java   
@Test
@RunAsClient
public void testSendMultipartSoapMessage() throws Exception {
   final MessageFactory msgFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
   final SOAPMessage msg = msgFactory.createMessage();
   final SOAPBodyElement bodyElement = msg.getSOAPBody().addBodyElement(
      new QName("urn:ledegen:soap-attachment:1.0", "echoImage"));
   bodyElement.addTextNode("cid:" + IN_IMG_NAME);

   final AttachmentPart ap = msg.createAttachmentPart();
   ap.setDataHandler(getResource("saaj/jbws3857/" + IN_IMG_NAME));
   ap.setContentId(IN_IMG_NAME);
   msg.addAttachmentPart(ap);

   final SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();
   final SOAPConnection connection = conFactory.createConnection();
   final SOAPMessage response = connection.call(msg, new URL("http://" + baseURL.getHost()+ ":" + baseURL.getPort() + "/" + PROJECT_NAME + "/testServlet"));

   final String contentTypeWeHaveSent = getBodyElementTextValue(response);
   assertContentTypeStarts("multipart/related", contentTypeWeHaveSent);
}
项目:onvif-java-lib    文件:SOAP.java   
protected SOAPMessage createSoapMessage(Object soapRequestElem, boolean needAuthentification) throws SOAPException, ParserConfigurationException,
        JAXBException {
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    SOAPMessage soapMessage = messageFactory.createMessage();

    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Marshaller marshaller = JAXBContext.newInstance(soapRequestElem.getClass()).createMarshaller();
    marshaller.marshal(soapRequestElem, document);
    soapMessage.getSOAPBody().addDocument(document);

    // if (needAuthentification)
    createSoapHeader(soapMessage);

    soapMessage.saveChanges();
    return soapMessage;
}
项目:infobip-open-jdk-8    文件:SAAJMetaFactoryImpl.java   
protected  MessageFactory newMessageFactory(String protocol)
    throws SOAPException {
    if (SOAPConstants.SOAP_1_1_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl();
    } else if (SOAPConstants.SOAP_1_2_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.ver1_2.SOAPMessageFactory1_2Impl();
    } else if (SOAPConstants.DYNAMIC_SOAP_PROTOCOL.equals(protocol)) {
          return new com.sun.xml.internal.messaging.saaj.soap.dynamic.SOAPMessageFactoryDynamicImpl();
    } else {
        log.log(
            Level.SEVERE,
            "SAAJ0569.soap.unknown.protocol",
            new Object[] {protocol, "MessageFactory"});
        throw new SOAPException("Unknown Protocol: " + protocol +
                                    "  specified for creating MessageFactory");
    }
}
项目:eHMP    文件:MviSoapConnection.java   
private SOAPMessage makeSOAPMessage(Object message) {
    LOG.debug("Converting POJO into SOAP message");
    try{
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Marshaller marshaller = JAXBContext.newInstance(message.getClass()).createMarshaller();
        marshaller.marshal(message, document);

        SOAPMessage soap = MessageFactory.newInstance().createMessage();
        soap.getSOAPBody().addDocument(document);
        soap.getSOAPPart().getEnvelope().setPrefix("soapenv");
        soap.getSOAPPart().getEnvelope().removeNamespaceDeclaration("SOAP-ENV");
        soap.getSOAPBody().setPrefix("soapenv");
        soap.getSOAPHeader().setPrefix("soapenv");
        soap.getSOAPBody().getFirstChild().setPrefix("vaww");

        return soap;
    } catch (Exception e){
        LOG.error("Unable to create SOAP message",e);
    }
    return null;
}
项目:wso2-axis2    文件:SOAPFaultTest.java   
@Test
public void testFaultCodeWithPrefix1() throws Exception {
    MessageFactory fac = MessageFactory.newInstance();
    SOAPMessage soapMessage = fac.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    SOAPBody body = envelope.getBody();
    SOAPFault sf = body.addFault();

    String prefix = "wso2";
    sf.setFaultCode(prefix + ":Server");
    String result = sf.getFaultCode();

    assertNotNull(result);
    assertEquals(prefix + ":Server", result);
}
项目:wso2-axis2    文件:PrefixesTest.java   
@Validated @Test
public void testAddingPrefixesForChildElements() throws Exception {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage msg = factory.createMessage();
    SOAPPart sp = msg.getSOAPPart();
    SOAPEnvelope se = sp.getEnvelope();
    SOAPBody sb = se.getBody();
    SOAPElement el1 = sb.addBodyElement(se.createName("element1",
                                                      "prefix1",
                                                      "http://www.sun.com"));
    el1.addChildElement(se.createName("element2",
                                      "prefix2",
                                      "http://www.apache.org"));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    msg.writeTo(baos);

    String xml = new String(baos.toByteArray());
    assertTrue(xml.indexOf("prefix1") != -1);
    assertTrue(xml.indexOf("prefix2") != -1);
    assertTrue(xml.indexOf("http://www.sun.com") != -1);
    assertTrue(xml.indexOf("http://www.apache.org") != -1);
}