Java Code Examples for javax.xml.soap.SOAPPart#getEnvelope()

The following examples show how to use javax.xml.soap.SOAPPart#getEnvelope() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractWsSender.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
protected SOAPMessageContext createSOAPMessageCtx(GenericRequest genericRequest) throws TechnicalConnectorException {
   try {
      SOAPMessage soapMessage = mf.createMessage();
      SOAPPart soapPart = soapMessage.getSOAPPart();
      if (genericRequest.isXopEnabled()) {
         soapMessage.getMimeHeaders().addHeader("Content-Type", "application/xop+xml");
         soapPart.addMimeHeader("Content-ID", "<[email protected]>");
         soapPart.addMimeHeader("Content-Transfer-Encoding", "8bit");
      }

      SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
      SOAPBody soapBody = soapEnvelope.getBody();
      soapBody.addDocument(genericRequest.getPayload());
      Map<String, DataHandler> handlers = genericRequest.getDataHandlerMap();

      AttachmentPart part;
      for(Iterator i$ = handlers.entrySet().iterator(); i$.hasNext(); soapMessage.addAttachmentPart(part)) {
         Entry<String, DataHandler> handlerEntry = (Entry)i$.next();
         DataHandler handler = (DataHandler)handlerEntry.getValue();
         part = soapMessage.createAttachmentPart(handler);
         part.setContentType(handler.getContentType());
         if (genericRequest.isXopEnabled()) {
            part.addMimeHeader("Content-Transfer-Encoding", "binary");
            part.setContentId("<" + (String)handlerEntry.getKey() + ">");
         } else {
            part.setContentId((String)handlerEntry.getKey());
         }
      }

      return createSOAPMessageCtx(soapMessage);
   } catch (SOAPException var11) {
      throw translate(var11);
   }
}
 
Example 2
Source File: SoapFaultHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getSoapFaultCode(SOAPMessage msg) throws SOAPException{
  	SOAPPart part = msg.getSOAPPart();
if(part !=null){
	SOAPEnvelope soapEnvelope = part.getEnvelope();
	if(soapEnvelope !=null){
	SOAPBody body = soapEnvelope.getBody();
		if(body !=null){
			SOAPFault fault=body.getFault();
			if(fault !=null && !StringUtils.isEmpty(fault.getFaultString()) && fault.getFaultString().contains("SOA-")){
				return fault.getFaultString();
			}
		}
	}
}
return null;
  }
 
Example 3
Source File: SoapFaultHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getSoapFaultCode(SOAPMessage msg) throws SOAPException{
  	SOAPPart part = msg.getSOAPPart();
if(part !=null){
	SOAPEnvelope soapEnvelope = part.getEnvelope();
	if(soapEnvelope !=null){
	SOAPBody body = soapEnvelope.getBody();
		if(body !=null){
			SOAPFault fault=body.getFault();
			if(fault !=null && !StringUtils.isEmpty(fault.getFaultString()) && fault.getFaultString().contains("SOA-")){
				return fault.getFaultString();
			}
		}
	}
}
return null;
  }
 
Example 4
Source File: InsurabilityHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void initMessageID(SOAPMessage msg) throws SOAPException {
	SOAPPart part = msg.getSOAPPart();
	if (part != null) {
		SOAPEnvelope soapEnvelope = part.getEnvelope();
		if (soapEnvelope != null) {
			SOAPHeader header = soapEnvelope.getHeader();
			
			if (header != null && header.getChildElements().hasNext()) {
				Node elementsResponseHeader = (Node) header.getChildElements().next();
				if (elementsResponseHeader != null && elementsResponseHeader.getLocalName() != null && elementsResponseHeader.getLocalName().equals("MessageID")) {
					NodeList elementsheader = elementsResponseHeader.getChildNodes();
					org.w3c.dom.Node element = elementsheader.item(0);
					messageId = element.getNodeValue();
					LOG.info("MyCareNet returned a response with messageId: " + messageId);
				}
			}
		}
	}
}
 
Example 5
Source File: SoapFaultHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getSoapFaultCode(SOAPMessage msg) throws SOAPException {
   SOAPPart part = msg.getSOAPPart();
   if (part != null) {
      SOAPEnvelope soapEnvelope = part.getEnvelope();
      if (soapEnvelope != null) {
         SOAPBody body = soapEnvelope.getBody();
         if (body != null) {
            SOAPFault fault = body.getFault();
            if (fault != null && !StringUtils.isEmpty(fault.getFaultString()) && fault.getFaultString().contains("SOA-")) {
               return fault.getFaultString();
            }
         }
      }
   }

   return null;
}
 
Example 6
Source File: InsurabilityHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void initMessageID(SOAPMessage msg) throws SOAPException {
	SOAPPart part = msg.getSOAPPart();
	if (part != null) {
		SOAPEnvelope soapEnvelope = part.getEnvelope();
		if (soapEnvelope != null) {
			SOAPHeader header = soapEnvelope.getHeader();
			
			if (header != null && header.getChildElements().hasNext()) {
				Node elementsResponseHeader = (Node) header.getChildElements().next();
				if (elementsResponseHeader != null && elementsResponseHeader.getLocalName() != null && elementsResponseHeader.getLocalName().equals("MessageID")) {
					NodeList elementsheader = elementsResponseHeader.getChildNodes();
					org.w3c.dom.Node element = elementsheader.item(0);
					messageId = element.getNodeValue();
					LOG.info("MyCareNet returned a response with messageId: " + messageId);
				}
			}
		}
	}
}
 
Example 7
Source File: SoapFaultHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getSoapFaultCode(SOAPMessage msg) throws SOAPException{
  	SOAPPart part = msg.getSOAPPart();
if(part !=null){
	SOAPEnvelope soapEnvelope = part.getEnvelope();
	if(soapEnvelope !=null){
	SOAPBody body = soapEnvelope.getBody();
		if(body !=null){
			SOAPFault fault=body.getFault();
			if(fault !=null && !StringUtils.isEmpty(fault.getFaultString()) && fault.getFaultString().contains("SOA-")){
				return fault.getFaultString();
			}
		}
	}
}
return null;
  }
 
Example 8
Source File: AbstractWsSender.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
protected SOAPMessageContext createSOAPMessageCtx(GenericRequest genericRequest) throws TechnicalConnectorException {
   try {
      SOAPMessage soapMessage = mf.createMessage();
      SOAPPart soapPart = soapMessage.getSOAPPart();
      if (genericRequest.isXopEnabled()) {
         soapMessage.getMimeHeaders().addHeader("Content-Type", "application/xop+xml");
         soapPart.addMimeHeader("Content-ID", "<[email protected]>");
         soapPart.addMimeHeader("Content-Transfer-Encoding", "8bit");
      }

      SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
      SOAPBody soapBody = soapEnvelope.getBody();
      soapBody.addDocument(genericRequest.getPayload());
      Map<String, DataHandler> handlers = genericRequest.getDataHandlerMap();

      AttachmentPart part;
      for(Iterator i$ = handlers.entrySet().iterator(); i$.hasNext(); soapMessage.addAttachmentPart(part)) {
         Entry<String, DataHandler> handlerEntry = (Entry)i$.next();
         DataHandler handler = (DataHandler)handlerEntry.getValue();
         part = soapMessage.createAttachmentPart(handler);
         part.setContentType(handler.getContentType());
         if (genericRequest.isXopEnabled()) {
            part.addMimeHeader("Content-Transfer-Encoding", "binary");
            part.setContentId("<" + (String)handlerEntry.getKey() + ">");
         } else {
            part.setContentId((String)handlerEntry.getKey());
         }
      }

      return createSOAPMessageCtx(soapMessage);
   } catch (SOAPException var11) {
      throw translate(var11);
   }
}
 
Example 9
Source File: ArcherAuthenticatingRestConnection.java    From FortifyBugTrackerUtility with MIT License 5 votes vote down vote up
public Long addValueToValuesList(Long valueListId, String value) {
	LOG.info("[Archer] Adding value '"+value+"' to value list id "+valueListId);
	// Adding items to value lists is not supported via REST API, so we need to revert to SOAP API
	// TODO Simplify this method?
	// TODO Make this method more fail-safe (like checking for the correct response element)?
	Long result = null;
	try {
		MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();
        SOAPElement bodyElement = body.addChildElement(envelope.createName("CreateValuesListValue", "", "http://archer-tech.com/webservices/"));
        bodyElement.addChildElement("sessionToken").addTextNode(tokenProviderRest.getToken());
        bodyElement.addChildElement("valuesListId").addTextNode(valueListId+"");
        bodyElement.addChildElement("valuesListValueName").addTextNode(value);
        message.saveChanges();
 
        SOAPMessage response = executeRequest(HttpMethod.POST, 
        		getBaseResource().path("/ws/field.asmx")
        		.request()
        		.header("SOAPAction", "\"http://archer-tech.com/webservices/CreateValuesListValue\"")
        		.accept("text/xml"),
        		Entity.entity(message, "text/xml"), SOAPMessage.class);
        @SuppressWarnings("unchecked")
		Iterator<Object> it = response.getSOAPBody().getChildElements();
        while (it.hasNext()){
        	Object o = it.next();
        	if ( o instanceof SOAPElement ) {	
        		result = new Long(((SOAPElement)o).getTextContent());
        	}
          }
        System.out.println(response);
	} catch (SOAPException e) {
		throw new RuntimeException("Error executing SOAP request", e);
	}
	return result;
}
 
Example 10
Source File: SignCodeMojo.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private static SOAPBody populateEnvelope(SOAPMessage message, String namespace)
        throws SOAPException {
    SOAPPart soapPart = message.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration(
            "soapenv","http://schemas.xmlsoap.org/soap/envelope/");
    envelope.addNamespaceDeclaration(
            namespace,"http://api.ws.symantec.com/webtrust/codesigningservice");
    return envelope.getBody();
}
 
Example 11
Source File: TestMustUnderstandHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public boolean handleMessage(SOAPMessageContext ctx) {

        boolean continueProcessing = true;

        try {
            Object b = ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
            boolean outbound = (Boolean)b;
            SOAPMessage msg = ctx.getMessage();
            if (isServerSideHandler()) {
                if (outbound) {
                    QName qname = new QName("http://cxf.apache.org/mu", "MU");
                    SOAPPart soapPart = msg.getSOAPPart();
                    SOAPEnvelope envelope = soapPart.getEnvelope();
                    SOAPHeader header = envelope.getHeader();
                    if (header == null) {
                        header = envelope.addHeader();
                    }


                    SOAPHeaderElement headerElement
                        = header.addHeaderElement(envelope.createName("MU", "ns1", qname.getNamespaceURI()));

                    // QName soapMustUnderstand = new QName("http://schemas.xmlsoap.org/soap/envelope/",
                    // "mustUnderstand");
                    Name name = SOAPFactory.newInstance()
                        .createName("mustUnderstand", "soap", "http://schemas.xmlsoap.org/soap/envelope/");
                    headerElement.addAttribute(name, "1");
                } else {
                    getHandlerInfoList(ctx).add(getHandlerId());
                }
            }
        } catch (SOAPException e) {
            e.printStackTrace();
        }
        return continueProcessing;
    }
 
Example 12
Source File: Tr064Comm.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets all required namespaces and prepares the SOAP message to send.
 * Creates skeleton + body data.
 *
 * @param bodyData
 *            is attached to skeleton to form entire SOAP message
 * @return ready to send SOAP message
 */
private SOAPMessage constructTr064Msg(SOAPBodyElement bodyData) {
    SOAPMessage soapMsg = null;

    try {
        MessageFactory msgFac;
        msgFac = MessageFactory.newInstance();
        soapMsg = msgFac.createMessage();
        soapMsg.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
        soapMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
        SOAPPart part = soapMsg.getSOAPPart();

        // valid for entire SOAP msg
        String namespace = "s";

        // create suitable fbox envelope
        SOAPEnvelope envelope = part.getEnvelope();
        envelope.setPrefix(namespace);
        envelope.removeNamespaceDeclaration("SOAP-ENV"); // delete standard namespace which was already set
        envelope.addNamespaceDeclaration(namespace, "http://schemas.xmlsoap.org/soap/envelope/");
        Name nEncoding = envelope.createName("encodingStyle", namespace,
                "http://schemas.xmlsoap.org/soap/encoding/");
        envelope.addAttribute(nEncoding, "http://schemas.xmlsoap.org/soap/encoding/");

        // create empty header
        SOAPHeader header = envelope.getHeader();
        header.setPrefix(namespace);

        // create body with command based on parameter
        SOAPBody body = envelope.getBody();
        body.setPrefix(namespace);
        body.addChildElement(bodyData); // bodyData already prepared. Needs only be added

    } catch (Exception e) {
        logger.error("Error creating SOAP message for fbox request with data {}", bodyData);
        e.printStackTrace();
    }

    return soapMsg;
}
 
Example 13
Source File: SOAPGenerator.java    From cougar with Apache License 2.0 5 votes vote down vote up
private static SOAPMessage generateSOAPMessageShell(HttpCallBean httpCallBean) {
	SOAPMessage message = null;
	String secNameSpace = "http://www.betfair.com/security/";
	httpCallBean.setServiceName("Baseline");
	String nameSpace = httpCallBean.getNameSpace();
	
	if(nameSpace==null || nameSpace.equals(""))
	{
		throw new RuntimeException("Namespace error invalid :" + nameSpace);
	}
	
	MessageFactory mf;

	try {
		mf = MessageFactory.newInstance();

		message = mf.createMessage();

		SOAPPart soapPart = message.getSOAPPart();
		SOAPEnvelope envelope = soapPart.getEnvelope();

		envelope.addNamespaceDeclaration("soapenv",
				"http://schemas.xmlsoap.org/soap/envelope/");
		envelope.addNamespaceDeclaration(BAS, nameSpace);

		envelope.addNamespaceDeclaration("sec", secNameSpace);

		// header
		envelope.getHeader().detachNode();
		SOAPHeader soapHeader = envelope.addHeader();

		Name header = envelope.createName("Header", "soapenv",
				"http://schemas.xmlsoap.org/soap/envelope/");

		soapHeader.addHeaderElement(header);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	return message;
}
 
Example 14
Source File: AbstractWsSender.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
protected SOAPMessageContext createSOAPMessageCtx(GenericRequest genericRequest) throws TechnicalConnectorException {
   try {
      SOAPMessage soapMessage = mf.createMessage();
      SOAPPart soapPart = soapMessage.getSOAPPart();
      if (genericRequest.isXopEnabled()) {
         soapMessage.getMimeHeaders().addHeader("Content-Type", "application/xop+xml");
         soapPart.addMimeHeader("Content-ID", "<[email protected]>");
         soapPart.addMimeHeader("Content-Transfer-Encoding", "8bit");
      }

      SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
      SOAPBody soapBody = soapEnvelope.getBody();
      soapBody.addDocument(genericRequest.getPayload());
      Map<String, DataHandler> handlers = genericRequest.getDataHandlerMap();

      AttachmentPart part;
      for(Iterator i$ = handlers.entrySet().iterator(); i$.hasNext(); soapMessage.addAttachmentPart(part)) {
         Entry<String, DataHandler> handlerEntry = (Entry)i$.next();
         DataHandler handler = (DataHandler)handlerEntry.getValue();
         part = soapMessage.createAttachmentPart(handler);
         part.setContentType(handler.getContentType());
         if (genericRequest.isXopEnabled()) {
            part.addMimeHeader("Content-Transfer-Encoding", "binary");
            part.setContentId("<" + (String)handlerEntry.getKey() + ">");
         } else {
            part.setContentId((String)handlerEntry.getKey());
         }
      }

      return createSOAPMessageCtx(soapMessage);
   } catch (SOAPException var11) {
      throw translate(var11);
   }
}
 
Example 15
Source File: AbstractWsSender.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
protected SOAPMessageContext createSOAPMessageCtx(GenericRequest genericRequest) throws TechnicalConnectorException {
   try {
      SOAPMessage soapMessage = mf.createMessage();
      SOAPPart soapPart = soapMessage.getSOAPPart();
      if (genericRequest.isXopEnabled()) {
         soapMessage.getMimeHeaders().addHeader("Content-Type", "application/xop+xml");
         soapPart.addMimeHeader("Content-ID", "<[email protected]>");
         soapPart.addMimeHeader("Content-Transfer-Encoding", "8bit");
      }

      SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
      SOAPBody soapBody = soapEnvelope.getBody();
      soapBody.addDocument(genericRequest.getPayload());
      Map<String, DataHandler> handlers = genericRequest.getDataHandlerMap();

      AttachmentPart part;
      for(Iterator i$ = handlers.entrySet().iterator(); i$.hasNext(); soapMessage.addAttachmentPart(part)) {
         Entry<String, DataHandler> handlerEntry = (Entry)i$.next();
         DataHandler handler = (DataHandler)handlerEntry.getValue();
         part = soapMessage.createAttachmentPart(handler);
         part.setContentType(handler.getContentType());
         if (genericRequest.isXopEnabled()) {
            part.addMimeHeader("Content-Transfer-Encoding", "binary");
            part.setContentId("<" + (String)handlerEntry.getKey() + ">");
         } else {
            part.setContentId((String)handlerEntry.getKey());
         }
      }

      return createSOAPMessageCtx(soapMessage);
   } catch (SOAPException var11) {
      throw translate(var11);
   }
}
 
Example 16
Source File: SecureSoapMessages.java    From spring-ws-security-soap-example with MIT License 5 votes vote down vote up
private static final SOAPMessage getMessageToSign(final String pathBase)
        throws SOAPException, IOException {
    final SOAPMessage soapMessage;
    final SOAPPart soapPart;
    final SOAPEnvelope soapEnvelope;
    final SOAPHeader soapHeader;
    final SOAPHeaderElement secElement;
    final SOAPElement binaryTokenElement;

    soapMessage = SoapMessageUtils.getMessage(pathBase);
    soapPart = soapMessage.getSOAPPart();
    soapEnvelope = soapPart.getEnvelope();
    soapHeader = soapEnvelope.getHeader();

    secElement = soapHeader.addHeaderElement(soapEnvelope.createName(
            "Security", "wsse",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"));
    binaryTokenElement = secElement.addChildElement(soapEnvelope.createName(
            "BinarySecurityToken", "wsse",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"));
    binaryTokenElement.setAttribute("EncodingType",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
    binaryTokenElement.setAttribute("ValueType",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");

    return soapMessage;
}
 
Example 17
Source File: SignCode.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private static SOAPBody populateEnvelope(SOAPMessage message, String namespace)
        throws SOAPException {
    SOAPPart soapPart = message.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration(
            "soapenv","http://schemas.xmlsoap.org/soap/envelope/");
    envelope.addNamespaceDeclaration(
            namespace,"http://api.ws.symantec.com/webtrust/codesigningservice");
    return envelope.getBody();
}
 
Example 18
Source File: JRXmlaQueryExecuter.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected SOAPMessage createQueryMessage()
{
	String queryStr = getQueryString();

	if (log.isDebugEnabled())
	{
		log.debug("MDX query: " + queryStr);
	}
	
	try
	{
		MessageFactory mf = MessageFactory.newInstance();
		SOAPMessage message = mf.createMessage();

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

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

		SOAPElement eEx = body.addChildElement(nEx);

		// add the parameters

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

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

		if (log.isDebugEnabled())
		{
			log.debug("XML/A query message: \n" + prettyPrintSOAP(message.getSOAPPart().getEnvelope()));
		}

		return message;
	}
	catch (SOAPException e)
	{
		throw new JRRuntimeException(e);
	}
}
 
Example 19
Source File: SimpleSecurityHandler.java    From onvif with Apache License 2.0 4 votes vote down vote up
@Override
public boolean handleMessage(final SOAPMessageContext msgCtx) {
  // System.out.println("SimpleSecurityHandler");

  // Indicator telling us which direction this message is going in
  final Boolean outInd = (Boolean) msgCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

  // Handler must only add security headers to outbound messages
  if (outInd.booleanValue()) {
    try {
      // Create the xml
      SOAPMessage soapMessage = msgCtx.getMessage();
      SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope();
      SOAPHeader header = envelope.getHeader();
      if (header == null) header = envelope.addHeader();

      SOAPPart sp = soapMessage.getSOAPPart();
      SOAPEnvelope se = sp.getEnvelope();
      se.addNamespaceDeclaration(WSSE_PREFIX, WSSE_NS);
      se.addNamespaceDeclaration(WSU_PREFIX, WSU_NS);

      SOAPElement securityElem = header.addChildElement(WSSE_LN, WSSE_PREFIX);
      // securityElem.setAttribute("SOAP-ENV:mustUnderstand", "1");

      SOAPElement usernameTokenElem =
          securityElem.addChildElement(USERNAME_TOKEN_LN, WSSE_PREFIX);

      SOAPElement usernameElem = usernameTokenElem.addChildElement(USERNAME_LN, WSSE_PREFIX);
      usernameElem.setTextContent(username);

      SOAPElement passwordElem = usernameTokenElem.addChildElement(PASSWORD_LN, WSSE_PREFIX);
      passwordElem.setAttribute(PASSWORD_TYPE_ATTR, PASSWORD_DIGEST);
      passwordElem.setTextContent(encryptPassword(password));

      SOAPElement nonceElem = usernameTokenElem.addChildElement(NONCE_LN, WSSE_PREFIX);
      nonceElem.setAttribute("EncodingType", BASE64_ENCODING);
      nonceElem.setTextContent(Base64.encodeBase64String(nonce.getBytes()));

      SOAPElement createdElem = usernameTokenElem.addChildElement(CREATED_LN, WSU_PREFIX);
      createdElem.setTextContent(getLastUTCTime());
    } catch (final Exception e) {
      e.printStackTrace();
      return false;
    }
  }
  return true;
}
 
Example 20
Source File: CompilatioAPIUtil.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public static Document callCompilatioReturnDocument(String apiURL, Map<String, String> parameters, String secretKey,
		final int timeout) throws TransientSubmissionException, SubmissionException {

	SOAPConnectionFactory soapConnectionFactory;
	Document xmlDocument = null;
	try {
		soapConnectionFactory = SOAPConnectionFactory.newInstance();

		SOAPConnection soapConnection = soapConnectionFactory.createConnection();

		MessageFactory messageFactory = MessageFactory.newInstance();
		SOAPMessage soapMessage = messageFactory.createMessage();
		SOAPPart soapPart = soapMessage.getSOAPPart();
		SOAPEnvelope envelope = soapPart.getEnvelope();
		SOAPBody soapBody = envelope.getBody();
		SOAPElement soapBodyAction = soapBody.addChildElement(parameters.get("action"));
		parameters.remove("action");
		// api key
		SOAPElement soapBodyKey = soapBodyAction.addChildElement("key");
		soapBodyKey.addTextNode(secretKey);

		Set<Entry<String, String>> ets = parameters.entrySet();
		Iterator<Entry<String, String>> it = ets.iterator();
		while (it.hasNext()) {
			Entry<String, String> param = it.next();
			SOAPElement soapBodyElement = soapBodyAction.addChildElement(param.getKey());
			soapBodyElement.addTextNode(param.getValue());
		}
		
		URL endpoint = new URL(null, apiURL, new URLStreamHandler() {
			@Override
			protected URLConnection openConnection(URL url) throws IOException {
				URL target = new URL(url.toString());
				URLConnection connection = target.openConnection();
				// Connection settings
				connection.setConnectTimeout(timeout);
				connection.setReadTimeout(timeout);
				return(connection);
			}
		});
		
		SOAPMessage soapResponse = soapConnection.call(soapMessage, endpoint);

		// loading the XML document
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		soapResponse.writeTo(out);
		DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
		builderfactory.setNamespaceAware(true);

		DocumentBuilder builder = builderfactory.newDocumentBuilder();
		xmlDocument = builder.parse(new InputSource(new StringReader(out.toString())));
		soapConnection.close();

	} catch (UnsupportedOperationException | SOAPException | IOException | ParserConfigurationException | SAXException e) {
		log.error(e.getLocalizedMessage(), e);
	}
	return xmlDocument;

}