/** @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();
    }
  }
  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");
    }
  }
Пример #3
0
  @Override
  protected boolean handleInbound(SOAPMessageContext msgContext) {
    try {
      SOAPMessage soapMessage = msgContext.getMessage();
      SOAPBody soapBody = soapMessage.getSOAPBody();

      SOAPBodyElement soapBodyElement = (SOAPBodyElement) soapBody.getChildElements().next();
      if (soapBodyElement.getChildElements().hasNext()) {
        SOAPElement payload = (SOAPElement) soapBodyElement.getChildElements().next();
        String value = payload.getValue();
        payload.setValue(value + "World");
      }
    } catch (SOAPException e) {
      throw new WebServiceException(e);
    }
    return true;
  }
Пример #4
0
  @Override
  public SOAPMessage getRequestSOAPMessage(String serviceNumber, RequestInfo requestInfo)
      throws Exception {
    String xChangeType = "";
    String applierNumber = "";
    String receiverNumber = "";
    String exchangeAmount = "";
    if (!StringUtils.isEmpty(requestInfo.getRequestBody().getExtParameters())) {
      JSONObject extParametersJson =
          new JSONObject(requestInfo.getRequestBody().getExtParameters());
      if (extParametersJson.has("xChangeType")) {
        xChangeType = extParametersJson.getString("xChangeType");
      } else {
        throw new Exception("xChangeType is null");
      }
      if (extParametersJson.has("applierNumber")) {
        applierNumber = extParametersJson.getString("applierNumber");
      } else {
        throw new Exception("applierNumber is null");
      }
      if (extParametersJson.has("receiverNumber")) {
        receiverNumber = extParametersJson.getString("receiverNumber");
      } else {
        throw new Exception("applierNumber is null");
      }
      if (extParametersJson.has("exchangeAmount")) {
        exchangeAmount = extParametersJson.getString("exchangeAmount");
      } else {
        throw new Exception("exchangeAmount is null");
      }
    }

    SOAPMessage message = SoapCallUtils.getMessageFactory().createMessage();
    this.getCBSArsHeader("XchangePromotionRequestMsg", message);
    SOAPBodyElement bodyElement = (SOAPBodyElement) message.getSOAPBody().getChildElements().next();
    SOAPElement reqestElement = bodyElement.addChildElement("XchangePromotionRequest");
    reqestElement.addChildElement("XchangeType", "arc").addTextNode(xChangeType);
    reqestElement.addChildElement("applierNumber", "arc").addTextNode(applierNumber);
    ;
    reqestElement.addChildElement("receiverNumber", "arc").addTextNode(receiverNumber);
    ;
    reqestElement.addChildElement("exchangeAmount", "arc").addTextNode(exchangeAmount);
    ;
    return message;
  }
 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);
   }
 }
Пример #6
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());
  }
Пример #7
0
 protected void createBody(SOAPBodyElement body, SOAPFactory spf) throws SOAPException {
   body.addChildElement(spf.createName("MaxEnvelopes")).setValue(String.valueOf(MaxEnvelopes));
 }
Пример #8
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 {

    }
  }
  /**
   * 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;
  }