示例#1
0
  public STElement call() throws IOException {
    try {
      soapRequest.saveChanges();
      if (debug) {
        System.out.print("********* REQUEST:");
        Element e = new DOMReader().read(soapRequest.getSOAPPart()).getRootElement();
        writer.write(e);
        System.out.println();
        System.out.println("------------------");
      }

      soapResponse = conn.call(soapRequest, wsdlURL);

      if (debug) {
        System.out.print("********* RESPONSE:");
        Element e = new DOMReader().read(soapResponse.getSOAPPart()).getRootElement();
        writer.write(e);
        System.out.println();
        System.out.println("------------------");
      }

      SOAPPart sp = soapResponse.getSOAPPart();
      SOAPEnvelope env = sp.getEnvelope();
      return new STElement(env.getBody());
    } catch (SOAPException e) {
      e.printStackTrace();
      return null;
    }
  }
  @Test
  public void testSWA() throws Exception {
    SOAPFactory soapFac = SOAPFactory.newInstance();
    MessageFactory msgFac = MessageFactory.newInstance();
    SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance();
    SOAPMessage msg = msgFac.createMessage();

    QName sayHi = new QName("http://apache.org/hello_world_rpclit", "sayHiWAttach");
    msg.getSOAPBody().addChildElement(soapFac.createElement(sayHi));
    AttachmentPart ap1 = msg.createAttachmentPart();
    ap1.setContent("Attachment content", "text/plain");
    msg.addAttachmentPart(ap1);
    AttachmentPart ap2 = msg.createAttachmentPart();
    ap2.setContent("Attachment content - Part 2", "text/plain");
    msg.addAttachmentPart(ap2);
    msg.saveChanges();

    SOAPConnection con = conFac.createConnection();
    URL endpoint =
        new URL("http://localhost:9008/SOAPServiceProviderRPCLit/SoapPortProviderRPCLit1");
    SOAPMessage response = con.call(msg, endpoint);
    QName sayHiResp = new QName("http://apache.org/hello_world_rpclit", "sayHiResponse");
    assertNotNull(response.getSOAPBody().getChildElements(sayHiResp));
    assertEquals(2, response.countAttachments());
  }
示例#3
0
  public SOAPMessage invoke(SOAPMessage request) {
    SOAPBody requestBody;
    try {
      requestBody = request.getSOAPBody();
      if (requestBody.getElementName().getLocalName().equals("Body")) {
        MessageFactory mf = MessageFactory.newInstance();
        SOAPFactory sf = SOAPFactory.newInstance();

        SOAPMessage response = mf.createMessage();
        SOAPBody respBody = response.getSOAPBody();
        Name bodyName;
        if (requestBody
            .getFirstChild()
            .getNextSibling()
            .getLocalName()
            .equals("getTomorrowForecast")) {
          bodyName = sf.createName("getTomorrowForecastResponse");
        } else if (requestBody.getFirstChild().getNextSibling().getLocalName().equals("invoke")) {
          bodyName = sf.createName("invokeResponse");
        } else {
          throw new SOAPException(
              "No operation named 'getTomorrowForecast' or 'invoke' was found !");
        }
        respBody.addBodyElement(bodyName);
        SOAPElement respContent = respBody.addChildElement("return");
        respContent.setValue(soapResponse);
        response.saveChanges();
        return response;
      }
    } catch (SOAPException soapEx) {
      logger.error("An error occurs !", soapEx);
    }
    return null;
  }
  /**
   * @param query the input of the user
   * @return SOAP message which is good for cross-platform web service
   */
  public SOAPMessage sendSOAPMessage(String query, URL serverURL) throws SOAPException {

    /** create a SOAP msg from query */
    SOAPMessage wsRequest = MessageFactory.newInstance().createMessage();

    // SOAP params
    SOAPPart part = wsRequest.getSOAPPart();
    SOAPEnvelope envelope = part.getEnvelope();
    SOAPBody body = envelope.getBody();

    // Name: a local name, a namespace prefix, and a namesapce URI.
    Name name = envelope.createName("query", "yyns", "http://cis555.co.nf/");
    SOAPElement elem = body.addChildElement(name);
    elem.addTextNode(query);
    //		body.addChildElement(envelope.createName("query", "yyns",
    // "http://cis555.co.nf/")).addTextNode(query);  //###
    wsRequest.saveChanges();

    /** send SOAP to P2P ring */
    // get response
    SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();
    SOAPMessage wsResponse = conn.call(wsRequest, serverURL);
    conn.close();
    return wsResponse;
  }
示例#5
0
  @Override
  public SOAPMessage invoke(SOAPMessage request) {
    SOAPMessage response = null;
    try {

      // store request
      File f = File.createTempFile("gen-AdviceOfReceipt", ".xml", new File("unit-test-data"));
      try (FileOutputStream fos = new FileOutputStream(f)) {
        request.writeTo(fos);
      }

      // response key!
      MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
      response = mf.createMessage();

      DOMResult drRes = new DOMResult(response.getSOAPPart());

      // generate AS4 Set message id and timestamp with xalan transformation or progamatically!!
      XMLUtils.deserialize(
          MSHServerTest.class.getResourceAsStream(
              "/test-samples/TEST_01-AdviceOfDelivery-Response.xml"),
          drRes);
      response.saveChanges();

    } catch (IOException ex) {
      Logger.getLogger(MSHTestProvider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SOAPException ex) {
      Logger.getLogger(MSHTestProvider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JAXBException ex) {
      Logger.getLogger(MSHTestProvider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TransformerException ex) {
      Logger.getLogger(MSHTestProvider.class.getName()).log(Level.SEVERE, null, ex);
    }
    return response;
  }
示例#6
0
  private SoapMessage makeInvocation(
      Map<String, String> outProperties, List<String> xpaths, Map<String, String> inProperties)
      throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);

    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    for (String key : outProperties.keySet()) {
      msg.put(key, outProperties.get(key));
    }

    handler.handleMessage(msg);

    doc = part;

    for (String xpath : xpaths) {
      assertValid(xpath, doc);
    }

    byte[] docbytes = getMessageBytes(doc);
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    for (String key : inProperties.keySet()) {
      inHandler.setProperty(key, inProperties.get(key));
    }

    inHandler.handleMessage(inmsg);

    return inmsg;
  }
 private void transportHeaders(Packet packet, boolean inbound, SOAPMessage msg)
     throws SOAPException {
   Map<String, List<String>> headers = getTransportHeaders(packet, inbound);
   if (headers != null) {
     addSOAPMimeHeaders(msg.getMimeHeaders(), headers);
   }
   if (msg.saveRequired()) msg.saveChanges();
 }
示例#8
0
  private void doTestSoapConnection(boolean disableChunking) throws Exception {
    SOAPFactory soapFac = SOAPFactory.newInstance();
    MessageFactory msgFac = MessageFactory.newInstance();
    SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance();
    SOAPMessage msg = msgFac.createMessage();

    if (disableChunking) {
      // this is the custom header checked by ServiceImpl
      msg.getMimeHeaders().addHeader("Transfer-Encoding-Disabled", "true");
      // this is a hint to SOAPConnection that the chunked encoding is not needed
      msg.getMimeHeaders().addHeader("Transfer-Encoding", "disabled");
    }

    QName sayHi = new QName("http://www.jboss.org/jbossws/saaj", "sayHello");
    msg.getSOAPBody().addChildElement(soapFac.createElement(sayHi));
    AttachmentPart ap1 = msg.createAttachmentPart();

    char[] content = new char[16 * 1024];
    Arrays.fill(content, 'A');

    ap1.setContent(new String(content), "text/plain");
    msg.addAttachmentPart(ap1);

    AttachmentPart ap2 = msg.createAttachmentPart();
    ap2.setContent("Attachment content - Part 2", "text/plain");
    msg.addAttachmentPart(ap2);
    msg.saveChanges();

    SOAPConnection con = conFac.createConnection();

    final String serviceURL = baseURL.toString();

    URL endpoint = new URL(serviceURL);
    SOAPMessage response = con.call(msg, endpoint);
    QName sayHiResp = new QName("http://www.jboss.org/jbossws/saaj", "sayHelloResponse");

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

    assertEquals(2, response.countAttachments());

    String[] values = response.getMimeHeaders().getHeader("Transfer-Encoding-Disabled");
    if (disableChunking) {
      // this means that the ServiceImpl executed the code branch verifying
      // that chunking was disabled
      assertNotNull(values);
      assertTrue(values.length == 1);
    } else {
      assertNull(values);
    }
  }
  public Document invokeMethod(DynamicBinder dBinder, Document inputDoc) throws ComponentException {
    try {
      logger.info(
          "URI : "
              + dBinder.wsdlURI
              + "\n porttype: "
              + dBinder.portType
              + " \n operation: "
              + dBinder.operation
              + "\n endpoint: "
              + dBinder.endPoint);

      QName serviceName = new QName(dBinder.targetNS, dBinder.serviceName);
      Service serv = Service.create(serviceName);

      QName portQName = new QName(dBinder.targetNS, dBinder.portType);
      serv.addPort(portQName, SOAPBinding.SOAP11HTTP_BINDING, dBinder.endPoint);

      MessageFactory factory = MessageFactory.newInstance();
      SOAPMessage message = factory.createMessage();

      // TODO: add namespaces declared on the SOAPBody level to the envelope
      message.getSOAPPart().getEnvelope().addNamespaceDeclaration("tns1", dBinder.targetNS);
      message.getSOAPBody().addDocument(inputDoc);
      message.getMimeHeaders().addHeader("SOAPAction", dBinder.operation);
      message.saveChanges();

      Dispatch<SOAPMessage> smDispatch =
          serv.createDispatch(portQName, SOAPMessage.class, Service.Mode.MESSAGE);

      List<Handler> handlers = smDispatch.getBinding().getHandlerChain();
      handlers.add(new SOAPLoggingHandler());
      smDispatch.getBinding().setHandlerChain(handlers);

      SOAPMessage soapResponse = null;
      try {
        soapResponse = smDispatch.invoke(message);
      } catch (Exception e) {
        logger.error("Fault has been returned in SOAP message!!!");
        return null;
      }

      return toDocument(soapResponse);
    } catch (Exception e) {
      logger.error(e.getMessage());
      throw new ComponentException(e.getMessage());
    }
  }
示例#10
0
  private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.cdyne.com/";

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

    /*
    Constructed SOAP Request Message:
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
        <SOAP-ENV:Header/>
        <SOAP-ENV:Body>
            <example:VerifyEmail>
                <example:email>[email protected]</example:email>
                <example:LicenseKey>123</example:LicenseKey>
            </example:VerifyEmail>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("*****@*****.**");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI + "VerifyEmail");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.print("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    System.out.println();

    return soapMessage;
  }
  @Override
  public boolean handleMessage(SOAPMessageContext context) {

    System.out.println("Client : handleMessage()......");

    Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    // if this is a request, true for outbound messages, false for inbound
    if (isRequest) {

      try {
        SOAPMessage soapMsg = context.getMessage();
        SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
        SOAPHeader soapHeader = soapEnv.getHeader();

        // if no header, add one
        if (soapHeader == null) {
          soapHeader = soapEnv.addHeader();
        }

        // add a soap header, name as "mac address"
        QName qname = new QName("http://service.coupon.ronx.com/", "couponList");
        SOAPHeaderElement soapHeaderElement = soapHeader.addHeaderElement(qname);

        soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
        //                soapHeaderElement.addTextNode(mac);
        soapMsg.saveChanges();

        // tracking
        soapMsg.writeTo(System.out);

      } catch (SOAPException | IOException e) {
        System.err.println(e);
      }
    }

    // continue other handler chain
    return true;
  }
  /** {@inheritDoc} */
  public SOAPMessage signSoapMessage(SOAPMessage msg, CredentialInfo credentialInfo)
      throws JAXRException {
    try {
      // Check if the server being communicated is a legacy server and property for it is set.
      boolean legacyServer =
          Boolean.valueOf(
                  CommonProperties.getInstance()
                      .getProperty("omar.common.security.legacyServer", "false"))
              .booleanValue();

      // Create XWSProcessor
      XWSSProcessorFactory factory = XWSSProcessorFactory.newInstance();
      XWSSProcessor processor = null;
      if (legacyServer) {
        processor =
            factory.createForSecurityConfiguration(
                getSecurityConfiguration(msg), new SecurityCallbackHandler(credentialInfo));
      } else {

        processor =
            factory.createForSecurityConfiguration(
                getSigningSecurityConfiguration(msg, credentialInfo),
                new SecurityCallbackHandler(credentialInfo));
      }
      ProcessingContext context = new ProcessingContext();

      // msg will be updated in place
      context.setSOAPMessage(msg);
      processor.secureOutboundMessage(context);

      // work around for SOAPMessage.writeTo() inconsistencies
      msg.saveChanges();
    } catch (Exception e) {
      throw new JAXRException(
          CommonResourceBundle.getInstance().getString("message.signSoapMessageFailed"), e);
    }

    return msg;
  }
示例#13
0
  @Test
  public void testCustomProcessorObject() throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);

    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);
    msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties");
    msg.put(WSHandlerConstants.USER, "myalias");
    msg.put("password", "myAliasPassword");

    handler.handleMessage(msg);

    doc = part;

    assertValid("//wsse:Security", doc);
    assertValid("//wsse:Security/ds:Signature", doc);

    byte[] docbytes = getMessageBytes(doc);
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    final Map<String, Object> properties = new HashMap<String, Object>();
    final Map<QName, Object> customMap = new HashMap<QName, Object>();
    customMap.put(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN), CustomProcessor.class);
    properties.put(WSS4JInInterceptor.PROCESSOR_MAP, customMap);
    WSS4JInInterceptor inHandler = new WSS4JInInterceptor(properties);

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);

    inHandler.handleMessage(inmsg);

    List<WSHandlerResult> results = getResults(inmsg);
    assertTrue(results != null && results.size() == 1);
    List<WSSecurityEngineResult> signatureResults =
        results.get(0).getActionResults().get(WSConstants.SIGN);
    assertTrue(signatureResults.size() == 1);

    Object obj = signatureResults.get(0).get("foo");
    assertNotNull(obj);
    assertEquals(obj.getClass().getName(), CustomProcessor.class.getName());
  }
示例#14
0
  @Validated
  @Test
  public void testHeaders() {
    try {
      // Create message factory and SOAP factory
      MessageFactory messageFactory = MessageFactory.newInstance();
      SOAPFactory soapFactory = SOAPFactory.newInstance();

      // Create a message
      SOAPMessage message = messageFactory.createMessage();

      // Get the SOAP header from the message and
      //  add headers to it
      SOAPHeader header = message.getSOAPHeader();

      String nameSpace = "ns";
      String nameSpaceURI = "http://gizmos.com/NSURI";

      Name order = soapFactory.createName("orderDesk", nameSpace, nameSpaceURI);
      SOAPHeaderElement orderHeader = header.addHeaderElement(order);
      orderHeader.setActor("http://gizmos.com/orders");

      Name shipping = soapFactory.createName("shippingDesk", nameSpace, nameSpaceURI);
      SOAPHeaderElement shippingHeader = header.addHeaderElement(shipping);
      shippingHeader.setActor("http://gizmos.com/shipping");

      Name confirmation = soapFactory.createName("confirmationDesk", nameSpace, nameSpaceURI);
      SOAPHeaderElement confirmationHeader = header.addHeaderElement(confirmation);
      confirmationHeader.setActor("http://gizmos.com/confirmations");

      Name billing = soapFactory.createName("billingDesk", nameSpace, nameSpaceURI);
      SOAPHeaderElement billingHeader = header.addHeaderElement(billing);
      billingHeader.setActor("http://gizmos.com/billing");

      // Add header with mustUnderstand attribute
      Name tName = soapFactory.createName("Transaction", "t", "http://gizmos.com/orders");

      SOAPHeaderElement transaction = header.addHeaderElement(tName);
      transaction.setMustUnderstand(true);
      transaction.addTextNode("5");

      // Get the SOAP body from the message but leave
      // it empty
      SOAPBody body = message.getSOAPBody();

      message.saveChanges();

      // Display the message that would be sent
      // System.out.println("\n----- Request Message ----\n");
      // message.writeTo(System.out);

      // Look at the headers
      Iterator allHeaders = header.examineAllHeaderElements();

      while (allHeaders.hasNext()) {
        SOAPHeaderElement headerElement = (SOAPHeaderElement) allHeaders.next();
        Name headerName = headerElement.getElementName();
        // System.out.println("\nHeader name is " +
        //                   headerName.getQualifiedName());
        // System.out.println("Actor is " + headerElement.getActor());
        // System.out.println("mustUnderstand is " +
        //                   headerElement.getMustUnderstand());
      }
    } catch (Exception e) {
      fail("Enexpected Exception " + e);
    }
  }
示例#15
0
  public boolean patientAndProviderEmailSend(
      String fromUser,
      String fromUserProvider,
      String toUser,
      String toUserProvider,
      String subject,
      String message) {
    String ret = "";
    // System.out.println("ticket: "+ticket);
    try {
      SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
      SOAPConnection conn = scf.createConnection();

      // Create message
      MessageFactory mf = MessageFactory.newInstance();
      SOAPMessage msg = mf.createMessage();

      // Object for message parts
      SOAPPart sp = msg.getSOAPPart();

      SOAPEnvelope env = sp.getEnvelope();
      env.addNamespaceDeclaration("soap", "http://schemas.xmlsoap.org/soap/envelop/");
      env.addNamespaceDeclaration("urn", "urn:gov:hhs:fha:nhinc:common:task");

      SOAPHeader header = env.getHeader();

      SOAPBody body = env.getBody();

      // Populate body
      SOAPElement be = body.addChildElement("SendMailTaskRequest", "urn");
      be.addChildElement("taskID", "urn").addTextNode(EMAIL_TASK_ID);
      be.addChildElement("fromUser", "urn").addTextNode(fromUser);
      be.addChildElement("fromUserProvider", "urn").addTextNode(fromUserProvider);
      be.addChildElement("toUser", "urn").addTextNode(toUser);
      be.addChildElement("toUserProvider", "urn").addTextNode(toUserProvider);
      be.addChildElement("subject", "urn").addTextNode(subject);
      be.addChildElement("message", "urn").addTextNode(message);
      //            be.addChildElement("ticket", "urn").addTextNode(ticket);
      //            be.addChildElement("action", "urn").addTextNode(action);
      //            be.addChildElement("message", "urn").addTextNode(message);
      //            be.addChildElement("patientID", "urn").addTextNode(patientId);

      // Save message
      msg.saveChanges();

      // View input
      // System.out.println("\n Soap request:\n");
      // msg.writeTo(System.out);

      // Send
      // String urlval = "http://208.75.163.61:8080/TaskManager/TaskManagerService";
      String urlval = getProperty("EmailSendEndpoint");
      SOAPMessage reply = conn.call(msg, urlval);

      // Create transformer
      TransformerFactory tff = TransformerFactory.newInstance();
      Transformer tf = tff.newTransformer();

      // Get reply content
      Source source = reply.getSOAPPart().getContent();
      Writer outWriter = new StringWriter();

      // Set output transformation
      // StreamResult result = new StreamResult(System.out);
      StreamResult result = new StreamResult(outWriter);

      // transfrom to get the xml
      tf.transform(source, result);

      // close connection
      conn.close();

      String xmlSource = outWriter.toString();
      ret = xmlSource;
      // System.out.println("mail test: "+ret);
    } catch (Exception e) {
      e.printStackTrace();
    }
    // assertTrue(ret.indexOf("<detail>Success</detail>")>0);
    if (ret.indexOf("<detail>Success</detail>") > 0) return true;
    return false;
  }
  protected SOAPMessage createQueryMessage() {
    String queryStr = getQueryString();

    if (log.isDebugEnabled()) {
      log.debug("MDX query: " + queryStr);
    }

    try {
      MessageFactory mf = MessageFactory.newInstance();
      SOAPMessage message = mf.createMessage();

      MimeHeaders mh = message.getMimeHeaders();
      mh.setHeader("SOAPAction", "\"urn:schemas-microsoft-com:xml-analysis:Execute\"");

      SOAPPart soapPart = message.getSOAPPart();
      SOAPEnvelope envelope = soapPart.getEnvelope();
      SOAPBody body = envelope.getBody();
      Name nEx = envelope.createName("Execute", "", XMLA_URI);

      SOAPElement eEx = body.addChildElement(nEx);

      // add the parameters

      // COMMAND parameter
      // <Command>
      // <Statement>queryStr</Statement>
      // </Command>
      Name nCom = envelope.createName("Command", "", XMLA_URI);
      SOAPElement eCommand = eEx.addChildElement(nCom);
      Name nSta = envelope.createName("Statement", "", XMLA_URI);
      SOAPElement eStatement = eCommand.addChildElement(nSta);
      eStatement.addTextNode(queryStr);

      // <Properties>
      // <PropertyList>
      // <DataSourceInfo>dataSource</DataSourceInfo>
      // <Catalog>catalog</Catalog>
      // <Format>Multidimensional</Format>
      // <AxisFormat>TupleFormat</AxisFormat>
      // </PropertyList>
      // </Properties>
      Map paraList = new HashMap();
      String datasource =
          (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_DATASOURCE);
      paraList.put("DataSourceInfo", datasource);
      String catalog =
          (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_CATALOG);
      paraList.put("Catalog", catalog);
      paraList.put("Format", "Multidimensional");
      paraList.put("AxisFormat", "TupleFormat");
      addParameterList(envelope, eEx, "Properties", "PropertyList", paraList);
      message.saveChanges();

      if (log.isDebugEnabled()) {
        log.debug("XML/A query message: " + message.toString());
      }

      return message;
    } catch (SOAPException e) {
      throw new JRRuntimeException(e);
    }
  }
示例#17
0
  SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException {
    boolean isFailure = false;

    URL url = null;
    HttpURLConnection httpConnection = null;

    int responseCode = 0;
    try {
      if (endPoint.getProtocol().equals("https"))
        // if(!setHttps)
        initHttps();
      // Process the URL
      JaxmURI uri = new JaxmURI(endPoint.toString());
      String userInfo = uri.getUserinfo();

      url = endPoint;

      if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri);

      // TBD
      //    Will deal with https later.
      if (!url.getProtocol().equalsIgnoreCase("http")
          && !url.getProtocol().equalsIgnoreCase("https")) {
        log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
        throw new IllegalArgumentException(
            "Protocol " + url.getProtocol() + " not supported in URL " + url);
      }
      httpConnection = (HttpURLConnection) createConnection(url);

      httpConnection.setRequestMethod("POST");

      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      httpConnection.setUseCaches(false);
      httpConnection.setInstanceFollowRedirects(true);

      if (message.saveRequired()) message.saveChanges();

      MimeHeaders headers = message.getMimeHeaders();

      Iterator it = headers.getAllHeaders();
      boolean hasAuth = false; // true if we find explicit Auth header
      while (it.hasNext()) {
        MimeHeader header = (MimeHeader) it.next();

        String[] values = headers.getHeader(header.getName());
        if (values.length == 1)
          httpConnection.setRequestProperty(header.getName(), header.getValue());
        else {
          StringBuffer concat = new StringBuffer();
          int i = 0;
          while (i < values.length) {
            if (i != 0) concat.append(',');
            concat.append(values[i]);
            i++;
          }

          httpConnection.setRequestProperty(header.getName(), concat.toString());
        }

        if ("Authorization".equals(header.getName())) {
          hasAuth = true;
          log.fine("SAAJ0091.p2p.https.auth.in.POST.true");
        }
      }

      if (!hasAuth && userInfo != null) {
        initAuthUserInfo(httpConnection, userInfo);
      }

      OutputStream out = httpConnection.getOutputStream();
      message.writeTo(out);

      out.flush();
      out.close();

      httpConnection.connect();

      try {

        responseCode = httpConnection.getResponseCode();

        // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        }
        // else if (responseCode != HttpURLConnection.HTTP_OK)
        // else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207))
        else if ((responseCode / 100) != 2) {
          log.log(
              Level.SEVERE,
              "SAAJ0008.p2p.bad.response",
              new String[] {httpConnection.getResponseMessage()});
          throw new SOAPExceptionImpl(
              "Bad response: (" + responseCode + httpConnection.getResponseMessage());
        }
      } catch (IOException e) {
        // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
        responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else {
          throw e;
        }
      }

    } catch (SOAPException ex) {
      throw ex;
    } catch (Exception ex) {
      log.severe("SAAJ0009.p2p.msg.send.failed");
      throw new SOAPExceptionImpl("Message send failed", ex);
    }

    SOAPMessage response = null;
    if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
      try {
        MimeHeaders headers = new MimeHeaders();

        String key, value;

        // Header field 0 is the status line so we skip it.

        int i = 1;

        while (true) {
          key = httpConnection.getHeaderFieldKey(i);
          value = httpConnection.getHeaderField(i);

          if (key == null && value == null) break;

          if (key != null) {
            StringTokenizer values = new StringTokenizer(value, ",");
            while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim());
          }
          i++;
        }

        InputStream httpIn =
            (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream());

        byte[] bytes = readFully(httpIn);

        int length =
            httpConnection.getContentLength() == -1
                ? bytes.length
                : httpConnection.getContentLength();

        // If no reply message is returned,
        // content-Length header field value is expected to be zero.
        if (length == 0) {
          response = null;
          log.warning("SAAJ0014.p2p.content.zero");
        } else {
          ByteInputStream in = new ByteInputStream(bytes, length);
          response = messageFactory.createMessage(headers, in);
        }

        httpIn.close();
        httpConnection.disconnect();

      } catch (SOAPException ex) {
        throw ex;
      } catch (Exception ex) {
        log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex);
        throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage());
      }
    }
    return response;
  }