/**
   * Given a binary token, create a {@link SOAPElement}
   *
   * @param token
   * @return
   * @throws SOAPException
   */
  private SOAPElement create(String token) throws SOAPException {
    if (factory == null) {
      factory = SOAPFactory.newInstance();
    }
    SOAPElement security =
        factory.createElement(Constants.WSSE_LOCAL, Constants.WSSE_PREFIX, Constants.WSSE_NS);

    if (valueTypeNamespace != null) {
      security.addNamespaceDeclaration(valueTypePrefix, valueTypeNamespace);
    }

    SOAPElement binarySecurityToken =
        factory.createElement(
            Constants.WSSE_BINARY_SECURITY_TOKEN, Constants.WSSE_PREFIX, Constants.WSSE_NS);
    binarySecurityToken.addTextNode(token);
    if (valueType != null && !valueType.isEmpty()) {
      binarySecurityToken.setAttribute(Constants.WSSE_VALUE_TYPE, valueType);
    }
    if (encodingType != null) {
      binarySecurityToken.setAttribute(Constants.WSSE_ENCODING_TYPE, encodingType);
    }

    security.addChildElement(binarySecurityToken);
    return security;
  }
  protected void parseAxesElement(SOAPElement axesElement) throws SOAPException {
    // Cycle over Axis-Elements
    Name aName = sf.createName("Axis", "", MDD_URI);
    Iterator itAxis = axesElement.getChildElements(aName);
    while (itAxis.hasNext()) {
      SOAPElement axisElement = (SOAPElement) itAxis.next();
      Name name = sf.createName("name");
      String axisName = axisElement.getAttributeValue(name);

      if (axisName.equals(SLICER_AXIS_NAME)) {
        continue;
      }

      // LookUp for the Axis
      JRXmlaResultAxis axis = xmlaResult.getAxisByName(axisName);

      // retrieve the tuples by <Tuples>
      name = sf.createName("Tuples", "", MDD_URI);
      Iterator itTuples = axisElement.getChildElements(name);
      if (itTuples.hasNext()) {
        SOAPElement eTuples = (SOAPElement) itTuples.next();
        handleTuplesElement(axis, eTuples);
      }
    }
  }
Ejemplo n.º 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;
  }
  protected void handleCellErrors(Iterator errorElems) throws SOAPException {
    SOAPElement errorElem = (SOAPElement) errorElems.next();

    StringBuffer errorMsg = new StringBuffer();
    errorMsg.append("Cell error: ");

    Iterator descriptionElems =
        errorElem.getChildElements(sf.createName("Description", "", MDD_URI));
    if (descriptionElems.hasNext()) {
      SOAPElement descrElem = (SOAPElement) descriptionElems.next();
      errorMsg.append(descrElem.getValue());
      errorMsg.append("; ");
    }

    Iterator sourceElems = errorElem.getChildElements(sf.createName("Source", "", MDD_URI));
    if (sourceElems.hasNext()) {
      SOAPElement sourceElem = (SOAPElement) sourceElems.next();
      errorMsg.append("Source: ");
      errorMsg.append(sourceElem.getValue());
      errorMsg.append("; ");
    }

    Iterator codeElems = errorElem.getChildElements(sf.createName("ErrorCode", "", MDD_URI));
    if (codeElems.hasNext()) {
      SOAPElement codeElem = (SOAPElement) codeElems.next();
      errorMsg.append("Code: ");
      errorMsg.append(codeElem.getValue());
      errorMsg.append("; ");
    }

    throw new JRRuntimeException(errorMsg.toString());
  }
  @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());
  }
  /**
   * Clear the soap MustUnderstand.
   *
   * @param soapHeader The SOAP header.
   * @param soapHeaderElement The SOAP header element.
   */
  private void clearMustUnderstand(
      final SOAPHeader soapHeader, final SOAPHeaderElement soapHeaderElement) throws SOAPException {
    final Name headerName = soapHeader.getElementName();

    final SOAPFactory factory = SOAPFactory.newInstance();
    final Name attributeName =
        factory.createName("mustUnderstand", headerName.getPrefix(), headerName.getURI());

    soapHeaderElement.removeAttribute(attributeName);
  }
Ejemplo n.º 7
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 CreateCoordinationContextResponseType createCoordinationContext(
      final CreateCoordinationContextType createCoordinationContext,
      final MAP map,
      boolean isSecure) {
    final String messageId = map.getMessageID();
    synchronized (messageIdMap) {
      messageIdMap.put(
          messageId, new CreateCoordinationContextDetails(createCoordinationContext, map));
      messageIdMap.notifyAll();
    }
    String coordinationType = createCoordinationContext.getCoordinationType();
    if (TestUtil.INVALID_CREATE_PARAMETERS_COORDINATION_TYPE.equals(coordinationType)) {
      try {
        SOAPFactory factory = SOAPFactory.newInstance();
        SOAPFault soapFault =
            factory.createFault(
                SoapFaultType.FAULT_SENDER.getValue(),
                CoordinationConstants.WSCOOR_ERROR_CODE_INVALID_PARAMETERS_QNAME);
        soapFault
            .addDetail()
            .addDetailEntry(CoordinationConstants.WSCOOR_ERROR_CODE_INVALID_PARAMETERS_QNAME)
            .addTextNode("Invalid create parameters");
        throw new SOAPFaultException(soapFault);
      } catch (Throwable th) {
        throw new ProtocolException(th);
      }
    }

    // we have to return a value so lets cook one up

    CreateCoordinationContextResponseType createCoordinationContextResponseType =
        new CreateCoordinationContextResponseType();
    CoordinationContext coordinationContext = new CoordinationContext();
    coordinationContext.setCoordinationType(coordinationType);
    coordinationContext.setExpires(createCoordinationContext.getExpires());
    String identifier = nextIdentifier();
    CoordinationContextType.Identifier identifierInstance =
        new CoordinationContextType.Identifier();
    identifierInstance.setValue(identifier);
    coordinationContext.setIdentifier(identifierInstance);
    W3CEndpointReferenceBuilder builder = new W3CEndpointReferenceBuilder();
    builder.serviceName(CoordinationConstants.REGISTRATION_SERVICE_QNAME);
    builder.endpointName(CoordinationConstants.REGISTRATION_ENDPOINT_QNAME);
    builder.address(TestUtil.PROTOCOL_COORDINATOR_SERVICE);
    W3CEndpointReference registrationService = builder.build();
    coordinationContext.setRegistrationService(TestUtil11.getRegistrationEndpoint(identifier));
    createCoordinationContextResponseType.setCoordinationContext(coordinationContext);

    return createCoordinationContextResponseType;
  }
  /**
   * @param authHeader
   * @param qnameAuthHeader
   * @param soapHeader
   * @return SOAPHeaderElement
   */
  private SOAPHeaderElement ProcessAuthHeader(
      AuthHeader authHeader, QName qnameAuthHeader, SOAPHeader soapHeader) {

    SOAPHeaderElement headerElement;

    try {
      /*
       * Create the authentication header element
       */
      headerElement = soapHeader.addHeaderElement(qnameAuthHeader);

      /*
       * Check if Identifier is specified
       */
      if (authHeader.getIdentifier() != null) {
        /*
         * Create Identifier element
         */
        QName qName =
            new QName(
                qnameAuthHeader.getNamespaceURI(),
                AuthHeader.STR_Identifier,
                qnameAuthHeader.getPrefix());
        SOAPElement element = soapFactory.createElement(qName);
        element.addTextNode(authHeader.getIdentifier());
        headerElement.addChildElement(element);
      }

      /*
       * Check if PassKey is specified
       */
      if (authHeader.getPasskey() != null) {
        /*
         * Create PassKey element
         */
        QName qName =
            new QName(
                qnameAuthHeader.getNamespaceURI(),
                AuthHeader.STR_Passkey,
                qnameAuthHeader.getPrefix());
        SOAPElement element = soapFactory.createElement(qName);
        element.addTextNode(authHeader.getPasskey());
        headerElement.addChildElement(element);
      }
    } catch (SOAPException ex) {
      headerElement = null;
    }

    return headerElement;
  }
Ejemplo n.º 10
0
 private static SOAPFactory createSoapFactory() {
   try {
     SOAPFactory factory = SOAPFactory.newInstance();
     Name name =
         factory.createName(
             CoordinationConstants.WSARJ_ELEMENT_INSTANCE_IDENTIFIER,
             CoordinationConstants.WSARJ_PREFIX,
             CoordinationConstants.WSARJ_NAMESPACE);
     WSARJ_ELEMENT_INSTANCE_NAME = name;
     return factory;
   } catch (SOAPException e) {
     // TODO log error here (should never happen)
   }
   return null;
 }
Ejemplo n.º 11
0
 private SOAPVersion(
     String httpBindingId,
     String nsUri,
     String contentType,
     String implicitRole,
     String roleAttributeName,
     String saajFactoryString,
     QName faultCodeMustUnderstand,
     String faultCodeClientLocalName,
     String faultCodeServerLocalName,
     Set<String> requiredRoles) {
   this.httpBindingId = httpBindingId;
   this.nsUri = nsUri;
   this.contentType = contentType;
   this.implicitRole = implicitRole;
   this.implicitRoleSet = Collections.singleton(implicitRole);
   this.roleAttributeName = roleAttributeName;
   try {
     saajMessageFactory = MessageFactory.newInstance(saajFactoryString);
     saajSoapFactory = SOAPFactory.newInstance(saajFactoryString);
   } catch (SOAPException e) {
     throw new Error(e);
   } catch (NoSuchMethodError e) {
     // SAAJ 1.3 is not in the classpath
     LinkageError x =
         new LinkageError("You are loading old SAAJ from " + Which.which(MessageFactory.class));
     x.initCause(e);
     throw x;
   }
   this.faultCodeMustUnderstand = faultCodeMustUnderstand;
   this.requiredRoles = requiredRoles;
   this.faultCodeClient = new QName(nsUri, faultCodeClientLocalName);
   this.faultCodeServer = new QName(nsUri, faultCodeServerLocalName);
 }
 protected void handleTuplesElement(JRXmlaResultAxis axis, SOAPElement tuplesElement)
     throws SOAPException {
   Name tName = sf.createName("Tuple", "", MDD_URI);
   for (Iterator itTuple = tuplesElement.getChildElements(tName); itTuple.hasNext(); ) {
     SOAPElement eTuple = (SOAPElement) itTuple.next();
     handleTupleElement(axis, eTuple);
   }
 }
  protected void handleHierInfo(JRXmlaResultAxis axis, SOAPElement hierInfoElement)
      throws SOAPException {
    Name name = sf.createName("name");
    String dimName = hierInfoElement.getAttributeValue(name); // Get the Dimension Name

    JRXmlaHierarchy hier = new JRXmlaHierarchy(dimName);
    axis.addHierarchy(hier);
  }
Ejemplo n.º 14
0
  /** @testStrategy: Create an OMElement, without using a builder. Verification of AXIS2-970 */
  public void test3() throws Exception {

    //    	 Step 1: Get the SAAJConverter object from the Factory
    SAAJConverterFactory f =
        (SAAJConverterFactory) FactoryRegistry.getFactory(SAAJConverterFactory.class);
    SAAJConverter converter = f.getSAAJConverter();

    // Stept 2: Create OM and parent SOAPElement
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace wrapNs = fac.createOMNamespace("namespace", "prefix");
    OMElement ome = fac.createOMElement("localname", wrapNs);
    SOAPFactory sf = SOAPFactory.newInstance();
    SOAPElement se = sf.createElement("name");

    // Step 3: Do the conversion
    converter.toSAAJ(ome, se, sf);
  }
Ejemplo n.º 15
0
  private SOAPFaultException createSOAPFaultException() {
    try {
      String namespace = "http://example.com/auctiontraq/schemas/doclit";
      SOAPFactory soapFactory = SOAPFactory.newInstance();
      Name name = soapFactory.createName("MySOAPFault", "ns0", namespace);
      Detail detail = soapFactory.createDetail();
      DetailEntry entry = detail.addDetailEntry(name);
      entry.addNamespaceDeclaration("data", namespace);
      Name attrName1 = soapFactory.createName("myAttr", "data", namespace);
      entry.addAttribute(attrName1, "myvalue");
      SOAPElement child = entry.addChildElement("message");
      child.addTextNode("Server Exception");

      Name name2 = soapFactory.createName("ExtraInformation", "ns0", namespace);
      DetailEntry entry2 = detail.addDetailEntry(name2);

      SOAPElement child2 = entry2.addChildElement("Reason");
      child2.addTextNode("Address Not Found");

      QName qname = new QName("http://schemas.xmlsoap.org/soap/envelope/", "server");
      SOAPFault sf = soapFactory.createFault("SOAP Fault Exception:Address Not Found", qname);
      org.w3c.dom.Node n = sf.getOwnerDocument().importNode(detail, true);
      sf.appendChild(n);
      return new SOAPFaultException(sf);
      // printDetail(detail);
      // return new SOAPFaultException(qname,
      //       "SOAP Fault Exception:Address Not Found", null, detail);

    } catch (SOAPException e) {
      e.printStackTrace();
      // QName qname = new QName("http://schemas.xmlsoap.org/soap/envelope/", "client");
      throw new WebServiceException("Exception While Creating SOAP Fault Exception", e);
    }
  }
  protected void parseCellDataElement(SOAPElement cellDataElement) throws SOAPException {
    Name name = sf.createName("Cell", "", MDD_URI);
    Iterator itCells = cellDataElement.getChildElements(name);
    while (itCells.hasNext()) {
      SOAPElement cellElement = (SOAPElement) itCells.next();

      Name errorName = sf.createName("Error", "", MDD_URI);
      Iterator errorElems = cellElement.getChildElements(errorName);
      if (errorElems.hasNext()) {
        handleCellErrors(errorElems);
      }

      Name ordinalName = sf.createName("CellOrdinal");
      String cellOrdinal = cellElement.getAttributeValue(ordinalName);

      Object value = null;
      Iterator valueElements = cellElement.getChildElements(sf.createName("Value", "", MDD_URI));
      if (valueElements.hasNext()) {
        SOAPElement valueElement = (SOAPElement) valueElements.next();
        String valueType = valueElement.getAttribute("xsi:type");
        if (valueType.equals("xsd:int")) {
          value = new Long(valueElement.getValue());
        } else if (valueType.equals("xsd:double")) {
          value = new Double(valueElement.getValue());
        } else if (valueType.equals("xsd:decimal")) {
          value = new Double(valueElement.getValue());
        } else {
          value = valueElement.getValue();
        }
      }

      String fmtValue = "";
      Iterator fmtValueElements =
          cellElement.getChildElements(sf.createName("FmtValue", "", MDD_URI));
      if (fmtValueElements.hasNext()) {
        SOAPElement fmtValueElement = ((SOAPElement) fmtValueElements.next());
        fmtValue = fmtValueElement.getValue();
      }

      int pos = Integer.parseInt(cellOrdinal);
      JRXmlaCell cell = new JRXmlaCell(value, fmtValue);
      xmlaResult.setCell(cell, pos);
    }
  }
 protected SOAPFault getSOAPFault(String content) {
   try {
     Document doc = XmlUtils.parseXml(content);
     SOAPEnvelope e =
         (SOAPEnvelope) SOAPFactory.newInstance().createElement(doc.getDocumentElement());
     SOAPFault fault = e.getBody().getFault();
     return fault;
   } catch (Exception e) {
     return null;
   }
 }
Ejemplo n.º 18
0
 /**
  * Create a SOAPElement representing an InstanceIdentifier
  *
  * @param instanceIdentifier the identifier string of the InstanceIdentifier being represented
  * @return a SOAPElement with the InstancreIdentifier QName as its element tag and a text node
  *     containing the suppliedidentifier string as its value
  */
 public static Element createInstanceIdentifierElement(String instanceIdentifier) {
   try {
     SOAPElement element = factory.createElement(WSARJ_ELEMENT_INSTANCE_NAME);
     element.addNamespaceDeclaration(
         CoordinationConstants.WSARJ_PREFIX, CoordinationConstants.WSARJ_NAMESPACE);
     element.addTextNode(instanceIdentifier);
     return element;
   } catch (SOAPException se) {
     // TODO log error here (should never happen)
     return null;
   }
 }
    private Element createUsernameToken(String usernameValue, String passwordValue)
        throws SOAPException {

      QName usernameTokenName =
          new QName(Constants.WSSE_NS, Constants.WSSE_USERNAME_TOKEN, Constants.WSSE_PREFIX);
      QName usernameName =
          new QName(Constants.WSSE_NS, Constants.WSSE_USERNAME, Constants.WSSE_PREFIX);
      QName passwordName =
          new QName(Constants.WSSE_NS, Constants.WSSE_PASSWORD, Constants.WSSE_PREFIX);
      QName createdName = new QName(Constants.WSU_NS, "Created", Constants.WSU_PREFIX);

      SOAPFactory factory = SOAPFactory.newInstance();
      SOAPElement usernametoken = factory.createElement(usernameTokenName);
      usernametoken.addNamespaceDeclaration(Constants.WSSE_PREFIX, Constants.WSSE_NS);
      usernametoken.addNamespaceDeclaration(Constants.WSU_PREFIX, Constants.WSU_NS);
      SOAPElement username = factory.createElement(usernameName);
      username.addTextNode(usernameValue);
      SOAPElement password = factory.createElement(passwordName);
      password.addAttribute(new QName("Type"), Constants.PASSWORD_TEXT_TYPE);
      password.addTextNode(passwordValue);

      SOAPElement created = factory.createElement(createdName);
      XMLGregorianCalendar createdCal =
          dataTypefactory.newXMLGregorianCalendar(new GregorianCalendar()).normalize();
      created.addTextNode(createdCal.toXMLFormat());

      usernametoken.addChildElement(username);
      usernametoken.addChildElement(password);
      usernametoken.addChildElement(created);
      return usernametoken;
    }
  protected void parseAxesInfoElement(SOAPElement axesInfoElement) throws SOAPException {
    // Cycle over AxisInfo-Elements
    Name axisInfoName = sf.createName("AxisInfo", "", MDD_URI);
    Iterator itAxis = axesInfoElement.getChildElements(axisInfoName);
    while (itAxis.hasNext()) {
      SOAPElement axisElement = (SOAPElement) itAxis.next();
      Name name = sf.createName("name");
      String axisName = axisElement.getAttributeValue(name);
      if (axisName.equals(SLICER_AXIS_NAME)) {
        continue;
      }

      JRXmlaResultAxis axis = new JRXmlaResultAxis(axisName);
      xmlaResult.addAxis(axis);

      // retrieve the hierarchies by <HierarchyInfo>
      name = sf.createName("HierarchyInfo", "", MDD_URI);
      Iterator itHierInfo = axisElement.getChildElements(name);
      while (itHierInfo.hasNext()) {
        SOAPElement eHierInfo = (SOAPElement) itHierInfo.next();
        handleHierInfo(axis, eHierInfo);
      }
    }
  }
Ejemplo n.º 21
0
  static SOAPFault createSoapFault(SOAPBinding binding, Exception ex) throws SOAPException {
    SOAPFault soapFault;
    try {
      soapFault = binding.getSOAPFactory().createFault();
    } catch (Throwable t) {
      // probably an old version of saaj or something that is not allowing createFault
      // method to work.  Try the saaj 1.2 method of doing this.
      try {
        soapFault = binding.getMessageFactory().createMessage().getSOAPBody().addFault();
      } catch (Throwable t2) {
        // still didn't work, we'll just throw what we have
        return null;
      }
    }

    if (ex instanceof SoapFault) {
      if (!soapFault.getNamespaceURI().equals(((SoapFault) ex).getFaultCode().getNamespaceURI())
          && SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE.equals(
              ((SoapFault) ex).getFaultCode().getNamespaceURI())) {
        // change to 1.1
        try {
          soapFault = SOAPFactory.newInstance().createFault();
        } catch (Throwable t) {
          // ignore
        }
      }
      soapFault.setFaultString(((SoapFault) ex).getReason());
      soapFault.setFaultCode(((SoapFault) ex).getFaultCode());
      soapFault.setFaultActor(((SoapFault) ex).getRole());

      Node nd = soapFault.getOwnerDocument().importNode(((SoapFault) ex).getOrCreateDetail(), true);
      nd = nd.getFirstChild();
      soapFault.addDetail();
      while (nd != null) {
        Node next = nd.getNextSibling();
        soapFault.getDetail().appendChild(nd);
        nd = next;
      }

    } else {
      String msg = ex.getMessage();
      if (msg != null) {
        soapFault.setFaultString(msg);
      }
    }
    return soapFault;
  }
  public JRDataSource createDatasource() throws JRException {
    try {
      this.sf = SOAPFactory.newInstance();
      this.connection = createSOAPConnection();
      SOAPMessage queryMessage = createQueryMessage();

      URL soapURL = new URL(getSoapUrl());
      SOAPMessage resultMessage = executeQuery(queryMessage, soapURL);

      xmlaResult = new JRXmlaResult();
      parseResult(resultMessage);
    } catch (MalformedURLException e) {
      throw new JRRuntimeException(e);
    } catch (SOAPException e) {
      throw new JRRuntimeException(e);
    }

    return new JROlapDataSource(dataset, xmlaResult);
  }
  protected void parseOLAPInfoElement(SOAPElement olapInfoElement) throws SOAPException {
    // CubeInfo-Element is not needed

    // Get the AxesInfo-Node
    Name axesInfoName = sf.createName("AxesInfo", "", MDD_URI);
    SOAPElement axesElement = null;
    Iterator axesInfoElements = olapInfoElement.getChildElements(axesInfoName);
    if (axesInfoElements.hasNext()) {
      Object axesObj = axesInfoElements.next();
      if (axesObj == null) {
        throw new JRRuntimeException("AxisInfo Element is null.");
      }
      axesElement = (SOAPElement) axesObj;
    } else {
      throw new JRRuntimeException("Could not retrieve AxesInfo Element.");
    }

    parseAxesInfoElement(axesElement);

    // CellInfo is not needed
  }
  protected void handleTupleElement(JRXmlaResultAxis axis, SOAPElement tupleElement)
      throws SOAPException {
    JRXmlaMemberTuple tuple = new JRXmlaMemberTuple(axis.getHierarchiesOnAxis().length);

    Name memName = sf.createName("Member", "", MDD_URI);
    Iterator itMember = tupleElement.getChildElements(memName);
    int memNum = 0;
    while (itMember.hasNext()) {
      SOAPElement memElement = (SOAPElement) itMember.next();

      Name name = sf.createName("Hierarchy", "", "");
      String hierName = memElement.getAttributeValue(name);

      String uName = "";
      Iterator uNameElements = memElement.getChildElements(sf.createName("UName", "", MDD_URI));
      if (uNameElements.hasNext()) {
        uName = ((SOAPElement) uNameElements.next()).getValue();
      }
      String caption = "";
      Iterator captionElements = memElement.getChildElements(sf.createName("Caption", "", MDD_URI));
      if (captionElements.hasNext()) {
        caption = ((SOAPElement) captionElements.next()).getValue();
      }
      String lName = "";
      Iterator lNameElements = memElement.getChildElements(sf.createName("LName", "", MDD_URI));
      if (lNameElements.hasNext()) {
        String levelUniqueName = ((SOAPElement) lNameElements.next()).getValue();
        Matcher matcher = LEVEL_UNIQUE_NAME_PATTERN.matcher(levelUniqueName);
        if (matcher.matches()) {
          lName = matcher.group(LEVEL_UNIQUE_NAME_PATTERN_NAME_GROUP);
        }
      }

      int lNum = 0;
      Iterator lNumElements = memElement.getChildElements(sf.createName("LNum", "", MDD_URI));
      if (lNumElements.hasNext()) {
        lNum = Integer.parseInt(((SOAPElement) lNumElements.next()).getValue());
      }
      JRXmlaMember member = new JRXmlaMember(caption, uName, hierName, lName, lNum);
      tuple.setMember(memNum++, member);
    }

    axis.addTuple(tuple);
  }
  @Override
  public boolean handleMessage(SOAPMessageContext messageContext) {
    boolean success = false;

    /*
     * Process the SOAP header for an outbound message
     */
    if ((Boolean) messageContext.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY) == true) {
      try {
        /*
         * Check if SOAPFactory instance have been created
         */
        if (soapFactory == null) {
          soapFactory = SOAPFactory.newInstance();
        }

        /*
         * Process the SOAP header to add the authentication information
         */
        this.ProcessSoapHeader(messageContext);

        /*
         * Write the finished SOAP message to system output
         */
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        messageContext.getMessage().writeTo(outputStream);
        //                System.out.println(outputStream.toString());

        success = true;
      } catch (SOAPException | IOException ex) {
        Logfile.WriteError(ex.toString());
      }
    }

    return success;
  }
  /**
   * 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;
  }
Ejemplo n.º 27
0
  /**
   * Find Base64 encoded certificate used to sign given message. No default constructor: Once
   * content has been created, remains unchanged for life of the instance.
   *
   * @param msg (received) SOAP message to parse
   * @exception JAXRException if any problem at all occurs, wrapping problems decoding content (from
   *     Base64) and any caught CertificateException or SOAPException
   */
  public ReceivedCertificate(SOAPMessage msg) throws JAXRException {
    // @wss:Id attribute value for <BinarySecurityToken/> element of interest
    final String tokenId = CanonicalConstants.CANONICAL_URI_SENDER_CERT;

    try {
      final Name binSecTokenName =
          SOAPFactory.newInstance().createName("BinarySecurityToken", "wsse", securityNS);

      SOAPHeader hdr = msg.getSOAPHeader();
      Iterator hdrElemIter = hdr.examineAllHeaderElements();
      while (hdrElemIter.hasNext()) {
        Object hdrElemObj = hdrElemIter.next();
        if (hdrElemObj instanceof SOAPHeaderElement) {
          // found a SOAP header element of some type
          SOAPHeaderElement hdrElem = (SOAPHeaderElement) hdrElemObj;
          if ((hdrElem.getLocalName().equals("Security"))
              && (hdrElem.getNamespaceURI().equals(securityNS))) {

            // found a <wss:Security/> element
            //                        Name binSecTokenName = SOAPFactory.newInstance().
            //			    createName("BinarySecurityToken", "wsse", securityNS);
            Iterator secTokensIter = hdrElem.getChildElements(binSecTokenName);
            while (secTokensIter.hasNext()) {
              Object binSecTokenObj = secTokensIter.next();
              if (binSecTokenObj instanceof Element) {
                // found a <BinarySecurityToken/> element
                Element binSecTokenElem = (Element) binSecTokenObj;
                String _tokenId = binSecTokenElem.getAttributeNS(securityUtilityNS, "Id");
                if (_tokenId.equals(tokenId)) {
                  // found propery identified element
                  if (null == cert) {
                    // found first cert content
                    InputStream is = null;
                    String encodedData = binSecTokenElem.getFirstChild().getNodeValue();
                    try {
                      try {
                        is = new ByteArrayInputStream(encodedData.getBytes("UTF-8"));
                        is = MimeUtility.decode(is, "base64");
                      } catch (Exception e) {
                        throw new JAXRException(
                            CommonResourceBundle.getInstance()
                                .getString("message.UnableToDecodeData"),
                            e);
                      }

                      CertificateFactory cf = CertificateFactory.getInstance("X.509");
                      cert = (X509Certificate) cf.generateCertificate(is);
                    } finally {
                      if (is != null) {
                        try {
                          is.close();
                        } catch (Exception e) {
                        }
                      }
                    }
                  } else {
                    // found second cert content
                    foundMultiple = true;
                    break;
                  }
                }
              }
            }
          }
        }
      }
    } catch (SOAPException e) {
      throw new JAXRException(
          CommonResourceBundle.getInstance().getString("message.CouldNotGetCertificate"), e);
    } catch (CertificateException e) {
      throw new JAXRException(
          CommonResourceBundle.getInstance().getString("message.CouldNotGetCertificate"), e);
    }
  }
Ejemplo n.º 28
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);
    }
  }
Ejemplo n.º 29
0
 protected void createBody(SOAPBodyElement body, SOAPFactory spf) throws SOAPException {
   body.addChildElement(spf.createName("MaxEnvelopes")).setValue(String.valueOf(MaxEnvelopes));
 }
  /**
   * 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 {

    }
  }