/** @param args */
  public static void main(String[] args) {
    try {
      MessageFactory factory = MessageFactory.newInstance();
      SOAPMessage soapMsg = factory.createMessage();
      SOAPPart part = soapMsg.getSOAPPart();

      SOAPEnvelope envelope = part.getEnvelope();
      SOAPHeader header = envelope.getHeader();
      SOAPBody body = envelope.getBody();

      header.addTextNode("Training Details");

      SOAPBodyElement element =
          body.addBodyElement(envelope.createName("JAVA", "training", "http://shivasoft.in/blog"));
      element.addChildElement("WS").addTextNode("Training on Web service");

      SOAPBodyElement element1 =
          body.addBodyElement(envelope.createName("JAVA", "training", "http://shivasoft.in/blog"));
      element1.addChildElement("Spring").addTextNode("Training on Spring 3.0");

      soapMsg.writeTo(System.out);
      FileOutputStream fOut = new FileOutputStream("SoapMessage.xml");
      soapMsg.writeTo(fOut);

      System.out.println();
      System.out.println("SOAP msg created");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 2
0
  // Watch out: this functionality affects Drools Server
  //
  // The problem seems to be related with the CXFProducer and the async processors,
  // and it only appears when we do a lookup for different sessions.
  // Using different sessions requires that camel switch classloader to execute commands
  // in the existing sessions. That could be realted too..
  // but in Drools Camel code I don't find any problem
  // The rest endpoint is working ok
  public void testCxfSoapSessionLookup() throws Exception {

    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
    QName payloadName = new QName("http://soap.jax.drools.org", "execute", "ns1");

    body.addBodyElement(payloadName);

    String cmd = "";
    cmd += "<batch-execution lookup=\"ksession1\">\n";
    cmd += "  <insert out-identifier=\"salaboy\" disconnected=\"true\">\n";
    cmd += "      <org.drools.springframework.Person2>\n";
    cmd += "         <name>salaboy</name>\n";
    cmd += "         <age>27</age>\n";
    cmd += "      </org.drools.springframework.Person2>\n";
    cmd += "   </insert>\n";
    cmd += "   <fire-all-rules/>\n";
    cmd += "</batch-execution>\n";

    body.addTextNode(cmd);

    Object object = this.context.createProducerTemplate().requestBody("direct://http", soapMessage);

    OutputStream out = new ByteArrayOutputStream();
    out = new ByteArrayOutputStream();
    soapMessage = (SOAPMessage) object;
    soapMessage.writeTo(out);
    String response = out.toString();
    assertTrue(response.contains("fact-handle identifier=\"salaboy\""));

    SOAPMessage soapMessage2 = MessageFactory.newInstance().createMessage();
    SOAPBody body2 = soapMessage.getSOAPPart().getEnvelope().getBody();
    QName payloadName2 = new QName("http://soap.jax.drools.org", "execute", "ns1");

    body2.addBodyElement(payloadName2);

    String cmd2 = "";
    cmd2 += "<batch-execution lookup=\"ksession2\">\n";
    cmd2 += "  <insert out-identifier=\"salaboy\" disconnected=\"true\">\n";
    cmd2 += "      <org.drools.springframework.Person3>\n";
    cmd2 += "         <name>salaboy</name>\n";
    cmd2 += "         <age>27</age>\n";
    cmd2 += "      </org.drools.springframework.Person3>\n";
    cmd2 += "   </insert>\n";
    cmd2 += "   <fire-all-rules/>\n";
    cmd2 += "</batch-execution>\n";

    body2.addTextNode(cmd2);

    Object object2 =
        this.context.createProducerTemplate().requestBody("direct://http", soapMessage2);

    OutputStream out2 = new ByteArrayOutputStream();
    out2 = new ByteArrayOutputStream();
    soapMessage2 = (SOAPMessage) object2;
    soapMessage2.writeTo(out2);
    String response2 = out2.toString();
    assertTrue(response2.contains("fact-handle identifier=\"salaboy\""));
  }
Ejemplo n.º 3
0
  public void addToSOAPBody(org.apache.axis.Message msg, XRoadProtocolHeader xRoadProtocolHeader) {
    try {
      // get SOAP envelope from SOAP message
      org.apache.axis.message.SOAPEnvelope se = msg.getSOAPEnvelope();
      SOAPBody body = se.getBody();

      @SuppressWarnings("rawtypes")
      Iterator items = body.getChildElements();
      if (items.hasNext()) {
        body.removeContents();
      }

      SOAPBodyElement element =
          body.addBodyElement(
              se.createName(
                  getSendingOptionsResponseType.DEFAULT_RESPONSE_ELEMENT_NAME,
                  CommonStructures.NS_DHL_PREFIX,
                  CommonStructures.NS_DHL_URI));

      if (xRoadProtocolHeader.getProtocolVersion().equals(XRoadProtocolVersion.V2_0)) {
        SOAPElement elParing = element.addChildElement(se.createName("paring"));
        elParing.addTextNode(this.dataMd5Hash);
      }

      // X-road "keha" part in SOAP message
      SOAPElement elKeha = element.addChildElement(se.createName("keha"));
      elKeha.addAttribute(se.createName("href"), "cid:" + kehaHref);
    } catch (Exception ex) {
      CommonMethods.logError(ex, this.getClass().getName(), "addToSOAPBody");
    }
  }
Ejemplo n.º 4
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;
  }
 public void process(Exchange exchange) throws Exception {
   InputStream is = (InputStream) exchange.getIn().getBody();
   // Bad Hack - Need to remote it and fix it in Camel (if it's a camel problem)
   // I need to copy the results here because I loose them at the end of the method
   String results = StringUtils.toString(is);
   if (is != null) {
     SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
     SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
     QName payloadName = new QName("http://soap.jax.drools.org/", "executeResponse", "ns1");
     QName responseName = new QName("http://soap.jax.drools.org/", "return", "ns1");
     SOAPBodyElement payload = body.addBodyElement(payloadName);
     SOAPElement response = payload.addChildElement(responseName);
     // Bad Hack - Need to remote it and fix it in Camel (if it's a camel problem)
     // response.addTextNode( StringUtils.toString( is ) );
     response.addTextNode(results);
     exchange.getOut().setBody(soapMessage);
   }
 }
  @Test
  public void testHandleMessage() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();

    String samlAssertion =
        "<Assertion xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\""
            + " AssertionID=\"_42e7a00652420d86ee884f295a3fbf02\">"
            + "</Assertion>";

    WSSecuritySOAPHandler testedInstance = new WSSecuritySOAPHandler();
    testedInstance.setPrivateKey(privateKey);
    testedInstance.setAssertion(samlAssertion);

    SOAPMessageContext mockSoapMessageContext = EasyMock.createMock(SOAPMessageContext.class);
    EasyMock.expect(mockSoapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY))
        .andReturn(true);

    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
    SOAPBody soapBody = soapEnvelope.getBody();
    soapBody.addBodyElement(new QName("http://www.example.com", "Test"));

    EasyMock.expect(mockSoapMessageContext.getMessage()).andReturn(soapMessage);

    // prepare
    EasyMock.replay(mockSoapMessageContext);

    // operate
    testedInstance.handleMessage(mockSoapMessageContext);

    // verify
    EasyMock.verify(mockSoapMessageContext);
    LOG.debug(toString(soapPart));
  }
 public String invokeServiceMethod(String methodName, String[] args) {
   try {
     MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
     SOAPMessage request = factory.createMessage();
     SOAPPart soap = request.getSOAPPart();
     SOAPEnvelope envelope = soap.getEnvelope();
     SOAPBody body = envelope.getBody();
     SOAPElement content = body.addBodyElement(new QName(serviceNs, methodName, "itu"));
     int c = 0;
     for (String arg : args) {
       SOAPElement name;
       name = content.addChildElement("arg" + c++);
       name.setTextContent(arg);
     }
     Dispatch<SOAPMessage> dispatch =
         webservice.createDispatch(port, SOAPMessage.class, Service.Mode.MESSAGE);
     SOAPMessage response = dispatch.invoke(request);
     String text = response.getSOAPBody().getTextContent();
     return text;
   } catch (SOAPException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 8
0
  public static void main(String[] args) throws SOAPException {
    // Service helloService = new HelloService();
    QName serviceName = new QName(targetNamespace, serName);
    QName portName = new QName(targetNamespace, pName);
    // Hello hello = helloService.getPortName();
    javax.xml.ws.Service service = Service.create(serviceName);
    service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
    Dispatch<SOAPMessage> dispatch =
        service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
    BindingProvider bp = (BindingProvider) dispatch;
    Map<String, Object> rc = bp.getRequestContext();
    rc.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
    rc.put(BindingProvider.SOAPACTION_URI_PROPERTY, OPER_NAME);
    MessageFactory factory = ((SOAPBinding) bp.getBinding()).getMessageFactory();

    SOAPMessage request = factory.createMessage();
    SOAPBody body = request.getSOAPBody();
    QName payloadName = new QName(targetNamespace, OPER_NAME, "ns1");
    SOAPBodyElement payload = body.addBodyElement(payloadName);
    SOAPElement message = payload.addChildElement(INPUT_NAME);
    message.addTextNode("x");
    //		String value = "<people>" +
    //				"<name>TimLu</name>"+
    //				"<age>26</age>"+
    //				"</people>";
    //		message.setValue(value);
    SOAPMessage reply = null;
    try {
      reply = dispatch.invoke(request);
    } catch (WebServiceException wse) {
      wse.printStackTrace();
    }
    SOAPBody soapBody = reply.getSOAPBody();
    SOAPBodyElement nextSoapBodyElement = (SOAPBodyElement) soapBody.getChildElements().next();
    SOAPElement soapElement = (SOAPElement) nextSoapBodyElement.getChildElements().next();
    System.out.println("Return repsone value=" + soapElement.getValue());
  }
Ejemplo n.º 9
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {

    String retval = "<html> <H4>";

    try {
      // Create a message factory.
      MessageFactory mf = MessageFactory.newInstance();

      // Create a message from the message factory.
      SOAPMessage msg = mf.createMessage();

      // Message creation takes care of creating the SOAPPart - a
      // required part of the message as per the SOAP 1.1
      // specification.
      SOAPPart sp = msg.getSOAPPart();

      // Retrieve the envelope from the soap part to start building
      // the soap message.
      SOAPEnvelope envelope = sp.getEnvelope();

      // Create a soap header from the envelope.
      SOAPHeader hdr = envelope.getHeader();

      // Create a soap body from the envelope.
      SOAPBody bdy = envelope.getBody();

      // Add a soap body element to the soap body
      SOAPBodyElement gltp =
          bdy.addBodyElement(
              envelope.createName("GetLastTradePrice", "ztrade", "http://wombat.ztrade.com"));

      gltp.addChildElement(envelope.createName("symbol", "ztrade", "http://wombat.ztrade.com"))
          .addTextNode("SUNW");

      StringBuffer urlSB = new StringBuffer();
      urlSB.append(req.getScheme()).append("://").append(req.getServerName());
      urlSB.append(":").append(req.getServerPort()).append(req.getContextPath());
      String reqBase = urlSB.toString();

      if (data == null) {
        data = reqBase + "/index.html";
      }

      // Want to set an attachment from the following url.
      // Get context
      URL url = new URL(data);

      AttachmentPart ap = msg.createAttachmentPart(new DataHandler(url));

      ap.setContentType("text/html");

      // Add the attachment part to the message.
      msg.addAttachmentPart(ap);

      // Create an endpoint for the recipient of the message.
      if (to == null) {
        to = reqBase + "/receiver";
      }

      URL urlEndpoint = new URL(to);

      System.err.println("Sending message to URL: " + urlEndpoint);
      System.err.println("Sent message is logged in \"sent.msg\"");

      retval += " Sent message (check \"sent.msg\") and ";

      FileOutputStream sentFile = new FileOutputStream("sent.msg");
      msg.writeTo(sentFile);
      sentFile.close();

      // Send the message to the provider using the connection.
      SOAPMessage reply = con.call(msg, urlEndpoint);

      if (reply != null) {
        FileOutputStream replyFile = new FileOutputStream("reply.msg");
        reply.writeTo(replyFile);
        replyFile.close();
        System.err.println("Reply logged in \"reply.msg\"");
        retval += " received reply (check \"reply.msg\").</H4> </html>";

      } else {
        System.err.println("No reply");
        retval += " no reply was received. </H4> </html>";
      }

    } catch (Throwable e) {
      e.printStackTrace();
      logger.severe("Error in constructing or sending message " + e.getMessage());
      retval += " There was an error " + "in constructing or sending message. </H4> </html>";
    }

    try {
      OutputStream os = resp.getOutputStream();
      os.write(retval.getBytes());
      os.flush();
      os.close();
    } catch (IOException e) {
      e.printStackTrace();
      logger.severe("Error in outputting servlet response " + e.getMessage());
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    try {
      if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(fif);
        List items = sfu.parseRequest(request);
        Iterator itr = items.iterator();
        FileItem image1 = null, image2 = null;
        if (itr.hasNext()) image1 = (FileItem) itr.next();
        if (itr.hasNext()) image2 = (FileItem) itr.next();
        byte[] bimage1 = new byte[(int) image1.getSize()];
        byte[] bimage2 = new byte[(int) image2.getSize()];

        InputStream in = image1.getInputStream();
        in.read(bimage1);
        in.close();
        in = image2.getInputStream();
        in.read(bimage2);
        byte[] img1 = new byte[bimage1.length];
        for (int i = 0; i < bimage1.length; ++i) img1[i] = bimage1[i];
        ByteArrayInputStream bais = new ByteArrayInputStream(img1);
        BufferedImage bufimg1 = ImageIO.read(bais);
        byte[] img2 = new byte[bimage2.length];
        for (int i = 0; i < bimage2.length; ++i) img2[i] = bimage2[i];
        ByteArrayInputStream bais1 = new ByteArrayInputStream(img2);
        BufferedImage bufimg2 = ImageIO.read(bais1);
        ProgressListener progressListener =
            new ProgressListener() {
              public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("We are currently reading item " + pItems);
                if (pContentLength == -1) {
                  System.out.println("So far, " + pBytesRead + " bytes have been read.");
                } else {
                  System.out.println(
                      "So far, " + pBytesRead + " of " + pContentLength + " bytes have been read.");
                }
              }
            };
        sfu.setProgressListener(progressListener);
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection wsdircon =
            DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:XE", "system", "imbagaming");
        PreparedStatement st =
            wsdircon.prepareStatement(
                "SELECT wsdl,count FROM WEBSERVICEDATABASE WHERE panorama='yes' and status='up' ORDER BY count");
        ResultSet rs = st.executeQuery();
        String wsdlString = "";
        int count = 0;
        if (rs.next()) {
          System.out.println(wsdlString = rs.getString(1));
          count = rs.getInt(2);
        } else {
          response.sendRedirect("effectchoosere.htm");
        }
        PreparedStatement st1 =
            wsdircon.prepareStatement(
                "UPDATE WEBSERVICEDATABASE SET count="
                    + (count
                        + (bufimg1.getWidth() * bufimg1.getHeight()
                            + bufimg2.getWidth() * bufimg2.getHeight()))
                    + "WHERE wsdl=\'"
                    + wsdlString
                    + "\'");
        System.out.println(count);
        st1.execute();

        // parse the wsdl and get the details from it

        URL wsdl = new URL(wsdlString);
        // URL wsdl=new URL("http://localhost:8084/IPWebServices/ImageProcess?wsdl");
        URLConnection conn = wsdl.openConnection();
        InputStream wsdlin = conn.getInputStream();
        BufferedReader bin = new BufferedReader(new InputStreamReader(wsdlin));
        char[] asdf = new char[1024 * 100];
        bin.read(asdf);
        String ss = new String(asdf);
        bin.close();
        wsdlin.close();
        String[] info = new String[6];
        info[0] = ss.substring(ss.indexOf("targetNamespace=\"") + 17, ss.indexOf("\" name"));
        System.out.println(info[0]);
        info[1] = ss.substring(ss.indexOf("name=\"") + 6, ss.indexOf("\">"));
        System.out.println(info[1]);
        info[2] = ss.substring(ss.indexOf("port name=\"") + 11, ss.indexOf("\" binding=\""));
        System.out.println(info[2]);
        info[3] = ss.substring(ss.indexOf("<message name=\"") + 15, ss.indexOf("\">\n<part"));

        // DII

        String svcName = info[1];
        String ns = info[0];
        QName svcQname = new QName(ns, svcName);
        String portName = info[2];
        QName portQname = new QName(ns, portName);
        Service service = Service.create(wsdl, svcQname);
        Dispatch<SOAPMessage> dispatch =
            service.createDispatch(portQname, SOAPMessage.class, Service.Mode.MESSAGE);
        SOAPMessage soapMsg = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMsg.getSOAPPart();
        SOAPEnvelope soapEnv = soapPart.getEnvelope();
        SOAPBody soapBody = soapEnv.getBody();
        Name bodyName = SOAPFactory.newInstance().createName("gogogo_1", "m", ns);
        SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
        Name param1 = SOAPFactory.newInstance().createName("image1");
        Name param2 = SOAPFactory.newInstance().createName("image2");
        Name param3 = SOAPFactory.newInstance().createName("effect");
        SOAPElement seimage1 = bodyElement.addChildElement(param1);
        SOAPElement seimage2 = bodyElement.addChildElement(param2);
        SOAPElement effect = bodyElement.addChildElement(param3);
        seimage1.addTextNode(Base64.encode(bimage1));
        seimage2.addTextNode(Base64.encode(bimage2));
        effect.addTextNode("panorama");
        SOAPMessage resp = dispatch.invoke(soapMsg);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // handle the response from web service to obtain the processed image

        resp.writeTo(baos);
        String saveImg = new String(baos.toByteArray());
        int lastI = saveImg.lastIndexOf("<return>") + 8;
        int firstI = saveImg.indexOf("</return>");
        saveImg = saveImg.substring(lastI, firstI);
        byte[] dwnld = new byte[saveImg.length()];
        dwnld = Base64.decode(saveImg);
        // decrease the count in the service directory

        PreparedStatement stc =
            wsdircon.prepareStatement(
                "SELECT count FROM WEBSERVICEDATABASE WHERE wsdl='" + wsdlString + "'");
        rs = stc.executeQuery();
        if (rs.next()) count = rs.getInt(1);
        count -=
            (bufimg1.getWidth() * bufimg1.getHeight() + bufimg2.getWidth() * bufimg2.getHeight());
        if (count < 0) count = 0;
        PreparedStatement st2 =
            wsdircon.prepareStatement(
                "UPDATE WEBSERVICEDATABASE SET count="
                    + (count)
                    + "WHERE wsdl=\'"
                    + wsdlString
                    + "\'");
        System.out.println(count);
        st2.execute();
        wsdircon.close();
        // redirect user to the download page

        ServletOutputStream op = response.getOutputStream();
        ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType("application/octet-stream");
        response.setContentLength(dwnld.length);
        response.setHeader(
            "Content-Disposition", "attachment; filename=\"" + "processedImage.jpg" + "\"");
        int length = 0;
        byte[] bbuf = new byte[1000];
        ByteArrayInputStream iin = new ByteArrayInputStream(dwnld);
        while ((iin != null) && ((length = iin.read(bbuf)) != -1)) {
          op.write(bbuf, 0, length);
        }
        // in.close();
        iin.close();
        op.flush();
        op.close();
      }
    } catch (Exception e) {
      System.out.println(e);
    } finally {

    }
  }
Ejemplo n.º 11
0
  public SOAPMessage buildPullMessage(
      URI uri, String enumerationContext, String resourceUri, int maxElements, int timeout)
      throws SOAPException {
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    SOAPMessage soapMessage = messageFactory.createMessage();

    SOAPEnvelope env = soapMessage.getSOAPPart().getEnvelope();
    env.removeNamespaceDeclaration(env.getPrefix());
    env.setPrefix("s");
    env.addNamespaceDeclaration("a", NS_WS_ADDRESSING);
    env.addNamespaceDeclaration("w", NS_WS_MANAGEMENT);
    env.addNamespaceDeclaration("n", NS_WS_ENUMERATION);
    env.addNamespaceDeclaration("ev", NS_WS_EVENTING);

    QName mustUnderstand = new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "mustUnderstand", "s");

    SOAPHeader soapHeader = soapMessage.getSOAPHeader();
    soapHeader.setPrefix("s");

    SOAPHeaderElement toHeader =
        soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "To", "a"));
    toHeader.setValue(uri.toString());

    SOAPHeaderElement resourceURI =
        soapHeader.addHeaderElement(new QName(NS_WS_MANAGEMENT, "ResourceURI", "w"));
    resourceURI.addAttribute(mustUnderstand, "true");
    resourceURI.setValue(resourceUri);

    SOAPHeaderElement replyTo =
        soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "ReplyTo", "a"));

    SOAPElement addressElement =
        replyTo.addChildElement(new QName(NS_WS_ADDRESSING, "Address", "a"));
    addressElement.addAttribute(mustUnderstand, "true");
    addressElement.addTextNode("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous");

    SOAPElement actionElement =
        soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "Action", "a"));
    actionElement.addAttribute(mustUnderstand, "true");
    actionElement.addTextNode(ENUMERATION_PULL);

    // MaxEnvelopeSize
    SOAPElement maxEnvelopeSize =
        soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "MaxEnvelopeSize", "w"));
    maxEnvelopeSize.addAttribute(mustUnderstand, "true");
    maxEnvelopeSize.addTextNode("51200");

    // Message ID
    SOAPElement messageId =
        soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "MessageID", "a"));
    messageId.addTextNode("uuid:" + UUID.randomUUID().toString());

    // Locale
    // SOAPElement locale = soapHeader.addChildElement(new
    // QName(NS_WS_MANAGEMENT, "Locale", "w"));
    // locale.addAttribute(mustUnderstand, "false");
    // locale.addAttribute(new QName("xml", "lang"), "en-US");

    SOAPElement operationTimeout =
        soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "OperationTimeout", "w"));
    operationTimeout.addTextNode(String.format("PT%d.000S", timeout));

    SOAPBody soapBody = soapMessage.getSOAPBody();
    soapBody.setPrefix("s");

    SOAPElement pullElement = soapBody.addBodyElement(new QName(NS_WS_ENUMERATION, "Pull", "n"));

    SOAPElement enumerationContextElement =
        pullElement.addChildElement(new QName(NS_WS_ENUMERATION, "EnumerationContext", "n"));
    enumerationContextElement.setTextContent(enumerationContext);

    // SOAPElement maxTime = pullElement.addChildElement(new
    // QName(NS_WS_ENUMERATION, "MaxTime", "n"));
    // maxTime.setTextContent("PS60S");

    SOAPElement maxElement =
        pullElement.addChildElement(new QName(NS_WS_ENUMERATION, "MaxElements", "n"));
    maxElement.setTextContent(String.valueOf(maxElements));

    // SOAPElement maxCharacters = pullElement.addChildElement(new
    // QName(NS_WS_ENUMERATION, "MaxCharacters", "n"));
    // enumerationContextElement.setTextContent("250000");

    return soapMessage;
  }
Ejemplo n.º 12
0
  public SOAPMessage buildWQLQuery(
      URI uri, String namespace, String query, int maxElements, int timeout) throws SOAPException {
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    SOAPMessage soapMessage = messageFactory.createMessage();

    SOAPEnvelope env = soapMessage.getSOAPPart().getEnvelope();
    env.removeNamespaceDeclaration(env.getPrefix());
    env.setPrefix("s");
    env.addNamespaceDeclaration("a", NS_WS_ADDRESSING);
    env.addNamespaceDeclaration("w", NS_WS_MANAGEMENT);
    env.addNamespaceDeclaration("en", NS_WS_ENUMERATION);

    QName mustUnderstand = new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "mustUnderstand", "s");

    SOAPHeader soapHeader = soapMessage.getSOAPHeader();
    soapHeader.setPrefix("s");

    SOAPHeaderElement toHeader =
        soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "To", "a"));
    toHeader.setValue(uri.toString());

    SOAPHeaderElement resourceURI =
        soapHeader.addHeaderElement(new QName(NS_WS_MANAGEMENT, "ResourceURI", "w"));
    resourceURI.addAttribute(mustUnderstand, "true");
    resourceURI.setValue(WSMAN_WMI_PREFIX + "/" + namespace + "/*");

    SOAPHeaderElement replyTo =
        soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "ReplyTo", "a"));

    SOAPElement addressElement =
        replyTo.addChildElement(new QName(NS_WS_ADDRESSING, "Address", "a"));
    addressElement.addAttribute(mustUnderstand, "true");
    addressElement.addTextNode("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous");

    SOAPElement actionElement =
        soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "Action", "a"));
    actionElement.addTextNode(ENUMERATION_ENUMERATE);

    // MaxEnvelopeSize
    SOAPElement maxEnvelopeSize =
        soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "MaxEnvelopeSize", "w"));
    maxEnvelopeSize.addAttribute(mustUnderstand, "true");
    maxEnvelopeSize.addTextNode("51200");

    // Message ID
    SOAPElement messageId =
        soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "MessageID", "a"));
    messageId.addTextNode("uuid:" + UUID.randomUUID().toString());

    // Locale
    // SOAPElement locale = soapHeader.addChildElement(new
    // QName(NS_WS_MANAGEMENT, "Locale", "w"));
    // locale.addAttribute(mustUnderstand, "false");
    // locale.addAttribute(new QName("xml", "lang"), "en-US");

    SOAPElement operationTimeout =
        soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "OperationTimeout", "w"));
    operationTimeout.addTextNode(String.format("PT%d.000S", timeout));

    SOAPBody soapBody = soapMessage.getSOAPBody();
    soapBody.setPrefix("s");

    SOAPElement enumerateElement =
        soapBody.addBodyElement(new QName(NS_WS_ENUMERATION, "Enumerate", "en"));

    // Return in the same response
    enumerateElement.addChildElement(new QName(NS_WS_MANAGEMENT, "OptimizeEnumeration", "w"));
    SOAPElement maxElement =
        enumerateElement.addChildElement(new QName(NS_WS_MANAGEMENT, "MaxElements", "w"));
    maxElement.addTextNode(String.valueOf(maxElements));
    SOAPElement filterElement =
        enumerateElement.addChildElement(new QName(NS_WS_MANAGEMENT, "Filter", "w"));
    filterElement.setAttribute("Dialect", DIALECT_WQL);
    filterElement.addTextNode(query);

    return soapMessage;
  }
Ejemplo n.º 13
0
  public SOAPMessage buildEventSubscription(
      URI uri, String subscriptionQuery, int maxElements, int timeout) throws SOAPException {
    // EVENT_LOG_NOTIFICATION_QUERY = """
    // SELECT * FROM __InstanceCreationEvent
    // WHERE TargetInstance ISA 'Win32_NTLogEvent'
    // AND TargetInstance.EventType <= %d
    // """
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    SOAPMessage soapMessage = messageFactory.createMessage();

    SOAPEnvelope env = soapMessage.getSOAPPart().getEnvelope();
    env.removeNamespaceDeclaration(env.getPrefix());
    env.setPrefix("s");
    env.addNamespaceDeclaration("a", NS_WS_ADDRESSING);
    env.addNamespaceDeclaration("w", NS_WS_MANAGEMENT);
    env.addNamespaceDeclaration("en", NS_WS_ENUMERATION);
    env.addNamespaceDeclaration("ev", NS_WS_EVENTING);

    QName mustUnderstand = new QName(SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE, "mustUnderstand", "s");

    SOAPHeader soapHeader = soapMessage.getSOAPHeader();
    soapHeader.setPrefix("s");

    SOAPHeaderElement toHeader =
        soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "To", "a"));
    toHeader.setValue(uri.toString());

    SOAPHeaderElement resourceURI =
        soapHeader.addHeaderElement(new QName(NS_WS_MANAGEMENT, "ResourceURI", "w"));
    resourceURI.addAttribute(mustUnderstand, "true");
    resourceURI.setValue(WSMAN_EVENTLOG_PREFIX);

    SOAPHeaderElement replyTo =
        soapHeader.addHeaderElement(new QName(NS_WS_ADDRESSING, "ReplyTo", "a"));

    SOAPElement addressElement =
        replyTo.addChildElement(new QName(NS_WS_ADDRESSING, "Address", "a"));
    addressElement.addAttribute(mustUnderstand, "true");
    addressElement.addTextNode("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous");

    SOAPElement actionElement =
        soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "Action", "a"));
    actionElement.addTextNode(EVENTING_SUBSCRIBE);

    // MaxEnvelopeSize
    SOAPElement maxEnvelopeSize =
        soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "MaxEnvelopeSize", "w"));
    maxEnvelopeSize.addAttribute(mustUnderstand, "true");
    maxEnvelopeSize.addTextNode("51200");

    // Message ID
    SOAPElement messageId =
        soapHeader.addChildElement(new QName(NS_WS_ADDRESSING, "MessageID", "a"));
    messageId.addTextNode("uuid:" + UUID.randomUUID().toString());

    // Locale
    // SOAPElement locale = soapHeader.addChildElement(new
    // QName(NS_WS_MANAGEMENT, "Locale", "w"));
    // locale.addAttribute(mustUnderstand, "false");
    // locale.addAttribute(new QName("xml", "lang"), "en-US");

    SOAPElement operationTimeout =
        soapHeader.addChildElement(new QName(NS_WS_MANAGEMENT, "OperationTimeout", "w"));
    operationTimeout.addTextNode(String.format("PT%d.000S", timeout));

    SOAPBody soapBody = soapMessage.getSOAPBody();
    soapBody.setPrefix("s");

    SOAPElement enumerateElement =
        soapBody.addBodyElement(new QName(NS_WS_EVENTING, "Subscribe", "ev"));

    SOAPElement deliveryElement =
        enumerateElement.addChildElement(new QName(NS_WS_EVENTING, "Delivery", "ev"));
    deliveryElement.setAttribute("Mode", "http://schemas.dmtf.org/wbem/wsman/1/wsman/Pull");

    SOAPElement expiresElement =
        enumerateElement.addChildElement(new QName(NS_WS_EVENTING, "Expires", "ev"));
    // EXPIRE in 60 seconds - don't do this normally!
    expiresElement.addTextNode(String.format("PT%dS", new Date().getTime() + 500)); // "PT60S");

    // <ev:Expires>[xs:dateTime | xs:duration]</ev:Expires>
    SOAPElement filterElement =
        enumerateElement.addChildElement(new QName(NS_WS_MANAGEMENT, "Filter", "w"));
    filterElement.setAttribute("Dialect", DIALECT_EVENTQUERY);

    // Need to convert the XML snippet specified in the subscriptionQuery
    try {
      filterElement.addChildElement(new Util().xmlToSOAPElement(subscriptionQuery));
    } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    // Tell them to send bookmarks so we can catch up later if we get
    // disconnected
    enumerateElement.addChildElement(new QName(NS_WS_MANAGEMENT, "SendBookmarks", "w"));

    return soapMessage;
  }
  /**
   * Create an STS client, create dispatch Invoke dispatch, return response
   *
   * @param args
   * @return
   * @throws SOAPException
   * @throws IOException
   * @throws SAXException
   * @throws ParserConfigurationException
   */
  public static String Go(
      String CSR,
      String SAN,
      String TemplateName,
      String CertFormat,
      String MEXuRI,
      String ValidUnit,
      String ValidValue,
      String OU1,
      String OU2,
      String OU3,
      String OU4,
      String OU5,
      String dnEmail)
      throws SOAPException, IOException, ParserConfigurationException, SAXException {

    MetadataClient mexClient = new MetadataClient();

    // the MEX URI is the service URL +/MEX
    Metadata metadata = mexClient.retrieveMetadata(MEXuRI + "/MEX");
    metadata.getOtherAttributes();

    QName serviceInfo = null;
    QName portName = null;
    String Address = null;
    // String namespace = null;

    List<PortInfo> ports = mexClient.getServiceInformation(metadata);
    for (PortInfo port : ports) {

      serviceInfo = port.getServiceName();
      portName = port.getPortName();
      Address = port.getAddress();
      // namespace = port.getPortNamespaceURI();

    }

    // an instance of SecurityTokenService
    Service STSS = Service.create(new URL(MEXuRI), serviceInfo);

    // a dispatch of SOAPMessage
    Dispatch<SOAPMessage> dispatch =
        STSS.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);

    // Message factor instance of SOAP 1.2 protcol
    MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);

    // Create SOAPMessage Request
    SOAPMessage request = factory.createMessage();

    // Request Header
    SOAPHeader header = request.getSOAPHeader();

    // Soap Factory
    SOAPFactory factory1 = SOAPFactory.newInstance();

    // Enable WS-Addressing and Add the "To:" endpoint
    SOAPElement To = factory1.createElement("To", "", "http://www.w3.org/2005/08/addressing");
    To.addTextNode(Address);

    // add the Microsoft MS-STEP Action Element:
    SOAPElement ActionElem =
        factory1.createElement("Action", "", "http://www.w3.org/2005/08/addressing");
    ActionElem.addTextNode("http://schemas.microsoft.com/windows/pki/2009/01/enrollment/RST/wstep");

    // Add a unique message ID "UUID"
    SOAPElement MessageID =
        factory1.createElement("MessageID", "", "http://www.w3.org/2005/08/addressing");
    MessageID.addTextNode("uuid:" + UUID.randomUUID());

    // add all the required SOAP header items:
    header.addChildElement(To);
    header.addChildElement(ActionElem);
    header.addChildElement(MessageID);

    // create a "Request Body" to hold request elements:
    SOAPBody body = request.getSOAPBody();

    // Compose the soap:Body payload "RequestSecurityToken" as the body type
    QName payloadName =
        new QName("http://docs.oasis-open.org/ws-sx/ws-trust/200512", "RequestSecurityToken", "");
    SOAPBodyElement payload = body.addBodyElement(payloadName);

    // Add the WS-Trust TokenType and RequestType elements:
    payload
        .addChildElement("TokenType")
        .addTextNode(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");
    payload
        .addChildElement("RequestType")
        .addTextNode("http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue");

    // add the BinarySecurityToken type
    SOAPElement BinarySecurityToken =
        factory1.createElement(
            "BinarySecurityToken",
            "",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

    // set BinarySecurityToken type as PKCS10 also known as a CSR..
    BinarySecurityToken.setAttribute(
        "ValueType", "http://schemas.microsoft.com/windows/pki/2009/01/enrollment#PKCS10");

    // Set the EncodingType to base64binary"
    BinarySecurityToken.setAttribute(
        "EncodingType",
        "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd#base64binary");

    // add the WSS wssSecurity namespace:
    BinarySecurityToken.addNamespaceDeclaration(
        "a", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

    // The CSR is Base64 encoded PKCS10 CSR without the "Begin" and "End" tags
    // add the CSR as a "TextNode"
    BinarySecurityToken.addTextNode(CSR);

    // add the BinarySecurityToken element to Soap pay load
    payload.addChildElement(BinarySecurityToken);

    // Create "AdditionalContext" Element for additional context items such as policy file name,
    // etc..
    QName AdditionalContextName =
        new QName("http://schemas.xmlsoap.org/ws/2006/12/authorization", "AdditionalContext", "");
    SOAPBodyElement AdditionalContext = body.addBodyElement(AdditionalContextName);

    // Create a ContextItem to specify the CertificateTemplate name, get
    // element from "TemplateName" argument
    SOAPElement ContextItem1 = AdditionalContext.addChildElement("ContextItem");
    ContextItem1.setAttribute("Name", "CertificateTemplate");
    SOAPElement Value = AdditionalContext.addChildElement("Value");
    Value.setTextContent(TemplateName);
    ContextItem1.addChildElement(Value);

    // Create a ContextItem to specify the value of "Other" context item
    // element from "TemplateName" argument
    SOAPElement ContextItem2 = AdditionalContext.addChildElement("ContextItem");
    ContextItem2.setAttribute("Name", "OU1");
    SOAPElement Value2 = AdditionalContext.addChildElement("Value");
    Value2.setTextContent(OU1);
    ContextItem2.addChildElement(Value2);

    // Create a ContextItem to specify the rmd (remote server) name
    SOAPElement ContextItem3 = AdditionalContext.addChildElement("ContextItem");
    ContextItem3.setAttribute("Name", "rmd");
    SOAPElement Value3 = AdditionalContext.addChildElement("Value");
    // Get application server FQDNS hostname
    InetAddress addr = InetAddress.getLocalHost();
    Value3.setTextContent(addr.getCanonicalHostName());
    ContextItem3.addChildElement(Value3);

    // Request specific validity period:

    // to enable client side to set validity period you must enable:
    // certutil -setreg Policy\EditFlags + EDITF_ATTRIBUTEENDDATE
    // on the CA!
    // Create a ContextItem to specify the rmd (remote server) name
    SOAPElement ContextItem4 = AdditionalContext.addChildElement("ContextItem");
    ContextItem4.setAttribute("Name", "ValidityPeriod");
    SOAPElement Value4 = AdditionalContext.addChildElement("Value");
    // Units can be "Seconds", "Minutes", "Hours", "Days", "Weeks", "Months", "Years"
    Value4.setTextContent(ValidUnit);
    ContextItem4.addChildElement(Value4);

    // Create a ContextItem to specify the rmd (remote server) name
    SOAPElement ContextItem5 = AdditionalContext.addChildElement("ContextItem");
    ContextItem5.setAttribute("Name", "ValidityPeriodUnits");
    SOAPElement Value5 = AdditionalContext.addChildElement("Value");
    Value5.setTextContent(ValidValue);
    ContextItem5.addChildElement(Value5);

    // Create a ContextItem to specify the value of "Other" context item
    // element from "TemplateName" argument
    SOAPElement ContextItem7 = AdditionalContext.addChildElement("ContextItem");
    ContextItem7.setAttribute("Name", "OU2");
    SOAPElement Value7 = AdditionalContext.addChildElement("Value");
    Value7.setTextContent(OU2);
    ContextItem7.addChildElement(Value7);

    // Create a ContextItem to specify the value of "Other" context item
    // element from "TemplateName" argument
    SOAPElement ContextItem8 = AdditionalContext.addChildElement("ContextItem");
    ContextItem8.setAttribute("Name", "OU3");
    SOAPElement Value8 = AdditionalContext.addChildElement("Value");
    Value8.setTextContent(OU3);
    ContextItem8.addChildElement(Value8);

    // Create a ContextItem to specify the value of "Other" context item
    // element from "TemplateName" argument
    SOAPElement ContextItem9 = AdditionalContext.addChildElement("ContextItem");
    ContextItem9.setAttribute("Name", "OU4");
    SOAPElement Value9 = AdditionalContext.addChildElement("Value");
    Value9.setTextContent(OU4);
    ContextItem9.addChildElement(Value9);

    // Create a ContextItem to specify the value of "Other" context item
    // element from "TemplateName" argument
    SOAPElement ContextItem10 = AdditionalContext.addChildElement("ContextItem");
    ContextItem10.setAttribute("Name", "OU5");
    SOAPElement Value10 = AdditionalContext.addChildElement("Value");
    Value10.setTextContent(OU5);
    ContextItem10.addChildElement(Value10);

    // KeyUsage=0xa0
    // SOAPElement ContextItem15 = AdditionalContext.addChildElement("ContextItem");
    // ContextItem15.setAttribute("Name", "CertificateUsage");
    // SOAPElement Value15 = AdditionalContext.addChildElement("Value");
    // Value15.setTextContent("1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2");
    // ContextItem15.addChildElement(Value15);

    // TODO:
    // let's try this an see what it does:
    // CertificateUsage

    // alternatively we can specify a specific end date:
    // ExpirationDate = L"Tue, 21 Nov 2000 01:06:53 GMT"

    // add the ContextItem child to the soap payload:
    AdditionalContext.addChildElement(ContextItem1);

    // TODO: document this, rename the context items
    AdditionalContext.addChildElement(ContextItem2);
    AdditionalContext.addChildElement(ContextItem3);
    // AdditionalContext.addChildElement(ContextItem4);
    // AdditionalContext.addChildElement(ContextItem5);
    AdditionalContext.addChildElement(ContextItem7);
    AdditionalContext.addChildElement(ContextItem8);
    AdditionalContext.addChildElement(ContextItem9);
    AdditionalContext.addChildElement(ContextItem10);
    // AdditionalContext.addChildElement(ContextItem15);

    // Create a ContextItem to specify the value of "Other" context item
    // element from "TemplateName" argument
    if (dnEmail != null) {
      SOAPElement ContextItem11 = AdditionalContext.addChildElement("ContextItem");
      ContextItem11.setAttribute("Name", "dnEmail");
      SOAPElement Value11 = AdditionalContext.addChildElement("Value");
      Value11.setTextContent(dnEmail);
      ContextItem11.addChildElement(Value11);
      AdditionalContext.addChildElement(ContextItem11);
    }

    // if SAN extention is specified add the ContextItem
    if (SAN != null) {
      // Create a ContextItem to specify the rmd (remote server) name
      SOAPElement ContextItem6 = AdditionalContext.addChildElement("ContextItem");
      ContextItem6.setAttribute("Name", "SAN");
      SOAPElement Value6 = AdditionalContext.addChildElement("Value");
      Value6.setTextContent(SAN);
      ContextItem6.addChildElement(Value6);
      AdditionalContext.addChildElement(ContextItem6);
    }

    payload.addChildElement(AdditionalContext);

    // place holder for RequestSecurityToken response soap message
    SOAPMessage reply = null;

    // Invoke the end point operation synchronously
    try {
      // and read response
      reply = dispatch.invoke(request);
    } catch (WebServiceException wse) {
      wse.printStackTrace();
    }

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

    // to view the reply via STD-Out:
    // System.out.println(baos);
    StringBuffer ressponseSB = new StringBuffer();
    String resonseS = baos.toString();

    ressponseSB.append(resonseS);
    StringBuilder sBuilder = RequestTokenResponseParser.ParseResponse(ressponseSB, CertFormat);

    String Certs = sBuilder.toString();

    return Certs;
  }