org.apache.axis.MessageContext Java Examples

The following examples show how to use org.apache.axis.MessageContext. 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: AxisClientImpl.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param context MessageContext
 * @return HandlerChain
 */
@Override
protected HandlerChain getJAXRPChandlerChain(MessageContext context) {
    QName portQName = (QName) context.getProperty(Call.WSDL_PORT_NAME);
    if (portQName == null) {
        return null;
    }
    String portName = portQName.getLocalPart();

    SeiFactory seiFactory = (SeiFactory) portNameToSEIFactoryMap.get(portName);
    if (seiFactory == null) {
        return null;
    }
    HandlerChain handlerChain = seiFactory.createHandlerChain();
    return handlerChain;
}
 
Example #2
Source File: DynamicWebServiceTypeGenerator.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public String generateType(CFCDescriptor d, MessageContext msgContext) throws IOException {
	Map<String, CFCSourceInfo> sMap = new FastMap<String, CFCSourceInfo>();
	Map<String, String> sBeanInfoMap = new FastMap<String, String>();
	List<DynamicCacheClassLoader> clList = new ArrayList<DynamicCacheClassLoader>();
	String name = UUID.generateKey();

	// Populate the necessary lists
	String dynClsName = prepareType(d, name, new FastMap<String, String>(false), sMap, sBeanInfoMap, clList);

	// Build the classes (if necessary)
	if (buildClasses(name, sMap, sBeanInfoMap, clList)) {
		// Link the DynamicCacheClassLoaders together (as dependents)
		linkClassLoaders(getClassLoader(dynClsName));
	}

	// Return the class name
	return dynClsName;
}
 
Example #3
Source File: cfcInvoker.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public Object invokeCFCFunction(MessageContext msgContext, cfSession session, String cfcName, cfStructData method, Object[] argValues) throws Exception {
	// Create the cfc
	cfComponentData cfc = new cfComponentData(session, cfcName);
	if (cfc == null || cfc.getMetaData() == null || cfc.getMetaData().isEmpty())
		throw new AxisFault(Messages.getMessage("noClassForService00", cfcName));

	// Convert the params
	cfArgStructData args = prepareArgs(session, method, argValues);

	// Execute the cfc
	cfData rtn = invokeComponentMethod(session, method, args, cfc);
	if (rtn == null || rtn instanceof cfNullData)
		return null;
	else {
		return tagUtils.getNatural(rtn, true, true, true);
	}
}
 
Example #4
Source File: AxisUtil.java    From j-road with Apache License 2.0 6 votes vote down vote up
public static String serialize(Object obj) throws IOException {
  TypeDesc desc = TypeDesc.getTypeDescForClass(obj.getClass());
  BeanSerializer serializer = new BeanSerializer(obj.getClass(), desc.getXmlType(), desc);

  MessageContext mctx = new MessageContext(null);
  mctx.setProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION, true);
  mctx.setProperty(AxisEngine.PROP_SEND_XSI, true);
  mctx.setTypeMappingRegistry(new TypeMappingRegistryImpl());

  StringWriter writer = new StringWriter();

  SerializationContext ctx = new SerializationContext(writer, mctx);
  ctx.setPretty(false);
  ctx.setSendDecl(true);
  ctx.setDoMultiRefs(false);

  serializer.serialize(new QName("keha"), new AttributesImpl(), obj, ctx);
  return writer.getBuffer().toString();
}
 
Example #5
Source File: HttpHandler.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(MessageContext msgContext) throws AxisFault {
  if (msgContext == null) {
    throw AxisFault.makeFault(new NullPointerException("Null message context"));
  }

  // Catch any exception thrown and wrap it in an AxisFault, per the contract of Handler.invoke.
  try {
    HttpResponse response = null;
    // Create the request.
    HttpRequest postRequest = createHttpRequest(msgContext);
    // Execute the request.
    response = postRequest.execute();
    // Translate the HTTP response to an Axis message on the message context.
    msgContext.setResponseMessage(createResponseMessage(response));
  } catch (RuntimeException | SOAPException | IOException e) {
    throw AxisFault.makeFault(e);
  }
}
 
Example #6
Source File: HttpHandlerTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/** Tests that a poorly formed XML response will result in an AxisFault. */
@Test
public void testInvokeReturnsInvalidXml() throws AxisFault {
  MessageContext messageContext = new MessageContext(axisEngine);

  messageContext.setRequestMessage(requestMessage);
  messageContext.setProperty(MessageContext.TRANS_URL, mockHttpServer.getServerUrl());
  messageContext.setProperty(HTTPConstants.MC_GZIP_REQUEST, true);
  mockHttpServer.setMockResponse(
      new MockResponse(
          "<?xml version='1.0' encoding='UTF-8' standalone='no'?>"
              + "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"
              + "foo..."));

  httpHandler.invoke(messageContext);

  // Expect parsing to fail. Tear down will verify the stream was closed.
  thrown.expect(AxisFault.class);
  messageContext.getResponseMessage().getSOAPEnvelope();
}
 
Example #7
Source File: HttpHandlerTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that a valid XML response results in a successful invocation of the handler that produces
 * a valid SOAP envelope.
 */
@Test
public void testInvokeReturnsValidXml() throws IOException {
  // Unlike the failure tests below, create the MessageContext here with an actual AxisClient,
  // not a mock AxisEngine. Otherwise, the call to getSOAPEnvelope below will fail.
  MessageContext messageContext = new MessageContext(new AxisClient());
  messageContext.setRequestMessage(requestMessage);
  messageContext.setProperty(MessageContext.TRANS_URL, mockHttpServer.getServerUrl());
  SoapResponseXmlProvider.getTestSoapResponse(API_VERSION);
  mockHttpServer.setMockResponse(
      new MockResponse(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)));

  httpHandler.invoke(messageContext);
  assertNotNull(
      "SOAP envelope of response is null", messageContext.getResponseMessage().getSOAPEnvelope());
}
 
Example #8
Source File: PojoProvider.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param msgContext msgContext
 * @param interfaceMethod interfaceMethod
 * @param pojo pojo
 * @param arguments arguments
 * @return
 * @throws Exception
 */
@Override
protected Object invokeMethod(MessageContext msgContext, Method interfaceMethod, Object pojo, Object[] arguments) throws Exception {
    Class pojoClass = pojo.getClass();

    Method pojoMethod = null;
    try {
        pojoMethod = pojoClass.getMethod(interfaceMethod.getName(), interfaceMethod.getParameterTypes());
    } catch (NoSuchMethodException e) {
        throw (NoSuchMethodException) new NoSuchMethodException("The pojo class '" + pojoClass.getName() + "' does not have a method matching signature: " + interfaceMethod).initCause(e);
    }

    return pojoMethod.invoke(pojo, arguments);
}
 
Example #9
Source File: EjbRpcProvider.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param msgContext msgContext
 * @param reqEnv reqEnv
 * @param resEnv resEnv
 * @param obj obj
 * @throws Exception
 */
@Override
public void processMessage(MessageContext msgContext, SOAPEnvelope reqEnv, SOAPEnvelope resEnv, Object obj) throws Exception {

    RPCElement body = getBody(reqEnv, msgContext);
    OperationDesc operation = getOperationDesc(msgContext, body);

    AxisRpcInterceptor interceptor = new AxisRpcInterceptor(operation, msgContext);
    SOAPMessage message = msgContext.getMessage();

    try {
        message.getSOAPPart().getEnvelope();
        msgContext.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, Boolean.FALSE);

        RpcContainer container = (RpcContainer) ejbDeployment.getContainer();

        Object[] arguments = {msgContext, interceptor};

        Class callInterface = ejbDeployment.getServiceEndpointInterface();
        Object result = container.invoke(ejbDeployment.getDeploymentID(), InterfaceType.SERVICE_ENDPOINT, callInterface, operation.getMethod(), arguments, null);

        interceptor.createResult(result);
    } catch (ApplicationException e) {
        interceptor.createExceptionResult(e.getCause());
    } catch (Throwable throwable) {
        throw new AxisFault("Web Service EJB Invocation failed: method " + operation.getMethod(), throwable);
    }
}
 
Example #10
Source File: getSOAPRequestHeader.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public cfData execute(cfSession _session, List<cfData> parameters) throws cfmRunTimeException {
	SOAPHeaderElement header = null;

	String ns = null;
	String n = null;
	boolean asXml = false;

	int offset = 0;
	if (parameters.size() == 3) {
		asXml = parameters.get(0).getBoolean();
		offset = 1;
	}
	n = parameters.get(0 + offset).getString();
	ns = parameters.get(1 + offset).getString();

	// Get the header
	try {
		MessageContext mc = MessageContext.getCurrentContext();
		if (mc != null && mc.getRequestMessage() != null && mc.getRequestMessage().getSOAPEnvelope() != null)
			header = mc.getRequestMessage().getSOAPEnvelope().getHeaderByName(ns, n);
		else
			throw new cfmRunTimeException(catchDataFactory.generalException("errorCode.runtimeError", "Could not get SOAP header. MessageContext request message is not available. " + "Be sure this is being called from a CFC web service function."));
	} catch (AxisFault ex) {
		throw new cfmRunTimeException(catchDataFactory.javaMethodException("errorCode.javaException", ex.getClass().getName(), ex.getMessage(), ex));
	}

	// Convert the header value into the desired cfData type
	return getSOAPHeaderValue(header, asXml);
}
 
Example #11
Source File: addSOAPResponseHeader.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public cfData execute(cfSession _session, List<cfData> parameters) throws cfmRunTimeException {
	String ns = null;
	String n = null;
	cfData val = null;
	boolean mustUnderstand = false;

	int offset = 0;
	if (parameters.size() == 4) {
		mustUnderstand = parameters.get(0).getBoolean();
		offset = 1;
	}
	val = parameters.get(0 + offset);
	n = parameters.get(1 + offset).getString();
	ns = parameters.get(2 + offset).getString();

	// Create the header
	SOAPHeaderElement header = addSOAPRequestHeader.createSOAPHeader(val, ns, n, mustUnderstand);

	// Add the header
	try {
		MessageContext mc = MessageContext.getCurrentContext();
		if (mc != null && mc.getResponseMessage() != null && mc.getResponseMessage().getSOAPEnvelope() != null) {
			// Check to see if the same header has already been added
			// (same meaning, having the same namespace/name pair)
			if (mc.getResponseMessage().getSOAPEnvelope().getHeaderByName(header.getNamespaceURI(), header.getName()) != null)
				throw new cfmRunTimeException(catchDataFactory.generalException("errorCode.runtimeError", "SOAP header value: " + header.getNamespaceURI() + ":" + header.getName() + " already set."));
			else
				mc.getResponseMessage().getSOAPEnvelope().addHeader(header);
		} else {
			throw new cfmRunTimeException(catchDataFactory.generalException("errorCode.runtimeError", "Could not set SOAP header value. MessageContext response message is not available. " + "Be sure this is being called from a CFC web service function."));
		}
	} catch (AxisFault ex) {
		throw new cfmRunTimeException(catchDataFactory.javaMethodException("errorCode.javaException", ex.getClass().getName(), ex.getMessage(), ex));
	}
	return cfBooleanData.TRUE;
}
 
Example #12
Source File: HttpHandler.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an HTTP request based on the message context.
 *
 * @param msgContext the Axis message context
 * @return a new {@link HttpRequest} with content and headers populated
 */
private HttpRequest createHttpRequest(MessageContext msgContext)
    throws SOAPException, IOException {
  Message requestMessage =
      Preconditions.checkNotNull(
          msgContext.getRequestMessage(), "Null request message on message context");
  
  // Construct the output stream.
  String contentType = requestMessage.getContentType(msgContext.getSOAPConstants());
  ByteArrayOutputStream bos = new ByteArrayOutputStream(BUFFER_SIZE);

  if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
    logger.debug("Compressing request");
    try (GZIPOutputStream gzipOs = new GZIPOutputStream(bos, BUFFER_SIZE)) {
      requestMessage.writeTo(gzipOs);
    }
  } else {
    logger.debug("Not compressing request");
    requestMessage.writeTo(bos);
  }

  HttpRequest httpRequest =
      requestFactory.buildPostRequest(
          new GenericUrl(msgContext.getStrProp(MessageContext.TRANS_URL)),
          new ByteArrayContent(contentType, bos.toByteArray()));

  int timeoutMillis = msgContext.getTimeout();
  if (timeoutMillis >= 0) {
    logger.debug("Setting read and connect timeout to {} millis", timeoutMillis);
    // These are not the same, but MessageContext has only one definition of timeout.
    httpRequest.setReadTimeout(timeoutMillis);
    httpRequest.setConnectTimeout(timeoutMillis);
  }

  // Copy the request headers from the message context to the post request.
  setHttpRequestHeaders(msgContext, httpRequest);

  return httpRequest;
}
 
Example #13
Source File: HttpHandler.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Sets HTTP request headers based on the Axis message context. */
private void setHttpRequestHeaders(MessageContext msgContext, HttpRequest httpRequest) {
  @SuppressWarnings("unchecked")
  Map<Object, Object> requestHeaders =
      (Map<Object, Object>) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);
  if (requestHeaders != null) {
    for (Entry<Object, Object> headerEntry : requestHeaders.entrySet()) {
      Object headerKey = headerEntry.getKey();
      if (headerKey == null) {
        continue;
      }
      String headerName = headerKey.toString().trim();
      Object headerValue = headerEntry.getValue();
      if (HTTPConstants.HEADER_AUTHORIZATION.equals(headerName)
          && (headerValue instanceof String)) {
        // HttpRequest expects the Authorization header to be a list of values,
        // so handle the case where it is simply a string.
        httpRequest.getHeaders().setAuthorization((String) headerValue);
      } else {
        httpRequest.getHeaders().set(headerName, headerValue);
      }
    }
  }
  if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
    httpRequest.getHeaders().setContentEncoding(HTTPConstants.COMPRESSION_GZIP);
  }
}
 
Example #14
Source File: HttpHandlerTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that a failed, non-XML response results in an AxisFault containing the HTTP status and
 * message.
 */
@Test
public void testInvokeReturnsNonXmlResponse() throws AxisFault {
  MessageContext messageContext = new MessageContext(axisEngine);
  messageContext.setRequestMessage(requestMessage);
  messageContext.setProperty(MessageContext.TRANS_URL, mockHttpServer.getServerUrl());
  messageContext.setProperty(HTTPConstants.MC_GZIP_REQUEST, true);
  MockResponse mockResponse = new MockResponse("Something went wrong", 500);
  mockResponse.setContentType("text/html");
  mockHttpServer.setMockResponse(mockResponse);

  // Expect an AxisFault based on the status code and content type.
  thrown.expect(AxisFault.class);
  httpHandler.invoke(messageContext);
}
 
Example #15
Source File: HttpHandlerTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Tests that a request with null content type will fail as expected. */
@Test
public void testInvokeWithoutContentType() throws AxisFault {
  MessageContext messageContext = new MessageContext(axisEngine);
  messageContext.setRequestMessage(requestMessage);
  messageContext.setProperty(MessageContext.TRANS_URL, mockHttpServer.getServerUrl());
  messageContext.setProperty(HTTPConstants.MC_GZIP_REQUEST, true);
  MockResponse mockResponse = new MockResponse("Something went wrong", 500);
  mockResponse.setContentType(null);
  mockHttpServer.setMockResponse(mockResponse);

  // Expect an AxisFault based on the status code and content type.
  thrown.expect(AxisFault.class);
  httpHandler.invoke(messageContext);
}
 
Example #16
Source File: HttpHandlerTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Tests that a request with null request on the message context will fail as expected. */
@Test
public void testInvokeWithoutRequestMessage() throws AxisFault {
  MessageContext messageContext = new MessageContext(axisEngine);

  thrown.expect(AxisFault.class);
  thrown.expectCause(Matchers.<Exception>instanceOf(NullPointerException.class));
  thrown.expectMessage("request");

  httpHandler.invoke(messageContext);
}
 
Example #17
Source File: HttpHandlerTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Tests that a request with null request URL will fail as expected. */
@Test
public void testInvokeWithoutRequestUrl() throws AxisFault {
  MessageContext messageContext = new MessageContext(axisEngine);
  messageContext.setRequestMessage(requestMessage);

  thrown.expect(AxisFault.class);
  thrown.expectCause(Matchers.<Exception>instanceOf(IllegalArgumentException.class));
  thrown.expectMessage("URL");

  httpHandler.invoke(messageContext);
}
 
Example #18
Source File: AbstractSDKService.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
protected IEngUserProfile getUserProfile() throws Exception {
	logger.debug("IN");
	IEngUserProfile profile = null;
	try {
		MessageContext mc = MessageContext.getCurrentContext();
		profile = (IEngUserProfile) mc.getProperty(IEngUserProfile.ENG_USER_PROFILE);
		if (profile == null) {
			logger.debug("User profile not found.");
			String userIdentifier = (String) mc.getProperty(WSHandlerConstants.USER);
			logger.debug("User identifier found = [" + userIdentifier + "].");
			if (userIdentifier == null) {
				logger.warn("User identifier not found!! cannot build user profile object");
				throw new Exception("Cannot create user profile");
			} else {
				try {
					profile = UserUtilities.getUserProfile(userIdentifier);
					logger.debug("User profile for userId [" + userIdentifier + "] created.");
				} catch (Exception e) {
					logger.error("Exception creating user profile for userId [" + userIdentifier + "]!", e);
					throw new Exception("Cannot create user profile");
				}
			}
			mc.setProperty(IEngUserProfile.ENG_USER_PROFILE, profile);
		} else {
			logger.debug("User profile for user [" + ((UserProfile) profile).getUserId() + "] retrieved.");
		}
		UserProfile userProfile = (UserProfile) profile;
		logger.info("User profile retrieved: userId = [" + userProfile.getUserId() + "]; username = [" + userProfile.getUserName() + "]");
	} finally {
		logger.debug("OUT");
	}
	return profile;
}
 
Example #19
Source File: HttpHandlerTest.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/** Tests that the timeout set on the message context is passed to the underlying request. */
@Test
public void testInvokeSetsTimeout() {
  MessageContext messageContext = new MessageContext(axisEngine);
  messageContext.setRequestMessage(requestMessage);
  messageContext.setProperty(MessageContext.TRANS_URL, "https://www.example.com");

  // Do not care about XML parsing for this test, so set the response's status code to 302
  // to trigger an AxisFault.
  MockLowLevelHttpResponse lowLevelHttpResponse = new MockLowLevelHttpResponse();
  lowLevelHttpResponse.setContent("Intentional failure");
  lowLevelHttpResponse.setStatusCode(302);

  /*
   * Set timeout on the message context, then create a custom mock transport that will capture
   * invocations of LowLevelHttpRequest.setTimeout(int, int) and record the arguments passed.
   */
  int timeout = 1234567;
  messageContext.setTimeout(timeout);
  final int[] actualTimeouts = new int[] {Integer.MIN_VALUE, Integer.MIN_VALUE};
  MockLowLevelHttpRequest lowLevelHttpRequest =
      new MockLowLevelHttpRequest() {
        @Override
        public void setTimeout(int connectTimeout, int readTimeout) throws IOException {
          actualTimeouts[0] = connectTimeout;
          actualTimeouts[1] = readTimeout;
          super.setTimeout(connectTimeout, readTimeout);
        }
      };
  lowLevelHttpRequest.setResponse(lowLevelHttpResponse);
  MockHttpTransport mockTransport =
      new MockHttpTransport.Builder().setLowLevelHttpRequest(lowLevelHttpRequest).build();
  httpHandler = new HttpHandler(mockTransport, streamListener);

  try {
    httpHandler.invoke(messageContext);
    fail("Expected an AxisFault");
  } catch (AxisFault e) {
    assertThat(e.getFaultString(), Matchers.containsString("302"));
  }
  assertArrayEquals(
      "Timeouts not set to expected values", new int[] {timeout, timeout}, actualTimeouts);
}
 
Example #20
Source File: ServerPWCallback.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
	logger.debug("IN");
	for (int i = 0; i < callbacks.length; i++) {
		if (callbacks[i] instanceof WSPasswordCallback) {
			WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
			String userId = pc.getIdentifier();
			logger.debug("UserId found from request: " + userId);
			if (pc.getUsage() == WSPasswordCallback.DECRYPT) {
				logger.debug("WSPasswordCallback.DECRYPT=" + WSPasswordCallback.DECRYPT);
				pc.setPassword("security");
				// } else if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN) {
				// logger.debug("WSPasswordCallback.USERNAME_TOKEN = " + pc.getUsage() + " callback usage");
				// // for passwords sent in digest mode we need to provide the password,
				// // because the original one can't be un-digested from the message
				// String password = getPassword(userId);
				// // this will throw an exception if the passwords don't match
				// pc.setPassword(password);
			} else if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN_UNKNOWN) {
				logger.debug("WSPasswordCallback.USERNAME_TOKEN_UNKNOWN = " + pc.getUsage() + " callback usage");
				// for passwords sent in clear-text mode we can compare passwords directly
				// Get the password that was sent
				String password = pc.getPassword();
				// Now pass them to your authentication mechanism
				SpagoBIUserProfile profile = authenticate(userId, password); // throws WSSecurityException.FAILED_AUTHENTICATION on failure
				logger.debug("New userId is " + profile.getUniqueIdentifier());
				userId = profile.getUniqueIdentifier();
			} else {
				logger.error("WSPasswordCallback usage [" + pc.getUsage() + "] not treated.");
				throw new UnsupportedCallbackException(callbacks[i], "WSPasswordCallback usage [" + pc.getUsage() + "] not treated.");
			}
			// Put userId into MessageContext (for services that depend on profiling)
			MessageContext mc = MessageContext.getCurrentContext();
			logger.debug("Setting userId to " + userId);
			mc.setProperty(WSHandlerConstants.USER, userId);
		} else {
			logger.error("Unrecognized Callback");
			throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
		}
	}
}
 
Example #21
Source File: EjbRpcProvider.java    From tomee with Apache License 2.0 4 votes vote down vote up
public AxisRpcInterceptor(OperationDesc operation, MessageContext msgContext) throws Exception {
    this.messageContext = msgContext;
    this.operation = operation;
}
 
Example #22
Source File: AxisDeserializer.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
public <ResultT> List<ResultT> deserializeBatchJobMutateResults(
    URL url,
    List<TypeMapping> serviceTypeMappings,
    Class<ResultT> resultClass,
    QName resultQName,
    int startIndex,
    int numberResults)
    throws Exception {

  List<ResultT> results = Lists.newArrayList();

  // Build a wrapped input stream from the response.
  InputStream wrappedStream =
      ByteSource.concat(
              ByteSource.wrap(SOAP_START_BODY.getBytes(UTF_8)),
              batchJobHelperUtility.buildWrappedByteSource(url, startIndex, numberResults),
              ByteSource.wrap(SOAP_END_BODY.getBytes(UTF_8)))
          .openStream();

  // Create a MessageContext with a new TypeMappingRegistry that will only
  // contain deserializers derived from serviceTypeMappings and the
  // result class/QName pair.
  MessageContext messageContext = new MessageContext(new AxisClient());
  TypeMappingRegistryImpl typeMappingRegistry = new TypeMappingRegistryImpl(true);
  messageContext.setTypeMappingRegistry(typeMappingRegistry);

  // Construct an Axis deserialization context.
  DeserializationContext deserializationContext =
      new DeserializationContext(
          new InputSource(wrappedStream), messageContext, Message.RESPONSE);

  // Register all type mappings with the new type mapping registry.
  TypeMapping registryTypeMapping =
      typeMappingRegistry.getOrMakeTypeMapping(messageContext.getEncodingStyle());
  registerTypeMappings(registryTypeMapping, serviceTypeMappings);

  // Parse the wrapped input stream.
  deserializationContext.parse();

  // Read the deserialized mutate results from the parsed stream.
  SOAPEnvelope envelope = deserializationContext.getEnvelope();
  MessageElement body = envelope.getFirstBody();

  for (Iterator<?> iter = body.getChildElements(); iter.hasNext(); ) {
    Object child = iter.next();
    MessageElement childElm = (MessageElement) child;
    @SuppressWarnings("unchecked")
    ResultT mutateResult = (ResultT) childElm.getValueAsType(resultQName, resultClass);
    results.add(mutateResult);
  }
  return results;
}
 
Example #23
Source File: SoapWrapper.java    From iaf with Apache License 2.0 4 votes vote down vote up
public String signMessage(String soapMessage, String user, String password, boolean passwordDigest) {
	try {
		WSSecurityEngine secEngine = WSSecurityEngine.getInstance();
		WSSConfig config = secEngine.getWssConfig();
		config.setPrecisionInMilliSeconds(false);

		// create context
		AxisClient tmpEngine = new AxisClient(new NullProvider());
		MessageContext msgContext = new MessageContext(tmpEngine);

		InputStream in = new ByteArrayInputStream(soapMessage.getBytes(StreamUtil.DEFAULT_INPUT_STREAM_ENCODING));
		Message msg = new Message(in);
		msg.setMessageContext(msgContext);

		// create unsigned envelope
		SOAPEnvelope unsignedEnvelope = msg.getSOAPEnvelope();
		Document doc = unsignedEnvelope.getAsDocument();

		// create security header and insert it into unsigned envelope
		WSSecHeader secHeader = new WSSecHeader();
		secHeader.insertSecurityHeader(doc);

		// add a UsernameToken
		WSSecUsernameToken tokenBuilder = new WSSecUsernameToken();
		if (passwordDigest) {
			tokenBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST);
		} else {
			tokenBuilder.setPasswordType(WSConstants.PASSWORD_TEXT);
		}
		tokenBuilder.setUserInfo(user, password);
		tokenBuilder.addNonce();
		tokenBuilder.addCreated();
		tokenBuilder.prepare(doc);

		WSSecSignature sign = new WSSecSignature();
		sign.setUsernameToken(tokenBuilder);
		sign.setKeyIdentifierType(WSConstants.UT_SIGNING);
		sign.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
		sign.build(doc, null, secHeader);

		tokenBuilder.prependToHeader(secHeader);

		// add a Timestamp
		WSSecTimestamp timestampBuilder = new WSSecTimestamp();
		timestampBuilder.setTimeToLive(300);
		timestampBuilder.prepare(doc);
		timestampBuilder.prependToHeader(secHeader);

		Document signedDoc = doc;

		return DOM2Writer.nodeToString(signedDoc);

	} catch (Exception e) {
		throw new RuntimeException("Could not sign message", e);
	}
}
 
Example #24
Source File: WandoraPiccoloWebapiService.java    From wandora with GNU General Public License v3.0 4 votes vote down vote up
protected TopicMap getTopicMap(){
    HttpServlet servlet=(HttpServlet)MessageContext.getCurrentContext().getProperty(org.apache.axis.transport.http.HTTPConstants.MC_HTTP_SERVLET);
    TopicMap tm=(TopicMap)servlet.getServletContext().getAttribute("org.wandora.PiccoloWandoraTopicMap");
    return tm;
}
 
Example #25
Source File: AxisContextHelper.java    From j-road with Apache License 2.0 4 votes vote down vote up
public MessageContext getMessageContext() {
  return messageContext;
}
 
Example #26
Source File: isSOAPRequest.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public cfData execute(cfSession _session, List<cfData> parameters) throws cfmRunTimeException {
	return ( MessageContext.getCurrentContext() == null ? cfBooleanData.FALSE : cfBooleanData.TRUE );
}
 
Example #27
Source File: cfcHandler.java    From openbd-core with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Returns a new cfSession from the specified MessageContext.
 * 
 * @param msgContext
 *          MessageContext for the current request.
 * @return a new cfSession from the specified MessageContext
 */
private cfSession getSession(MessageContext msgContext) {
	HttpServletRequest req = (HttpServletRequest) msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
	HttpServletResponse res = (HttpServletResponse) msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETRESPONSE);
	ServletContext ctxt = req.getSession(true).getServletContext();
	return new cfSession(req, res, ctxt);
}
 
Example #28
Source File: cfcProvider.java    From openbd-core with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Fill in a service description with the correct impl class and typemapping
 * set. This uses methods that can be overridden by other providers (like the
 * EJBProvider) to get the class from the right place.
 * 
 * @param service
 *          SOAPService wrapper
 * @param msgContext
 *          MessageContext for this SOAPService
 * @throws AxisFault
 */
public void initServiceDesc(SOAPService service, MessageContext msgContext) throws AxisFault {
	// Normal initialization
	super.initServiceDesc(service, msgContext);

	// Remove the IComplexObject operations
	removeIComplexObjectOps(service.getServiceDescription());
}
 
Example #29
Source File: PojoProvider.java    From tomee with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @param msgContext msgContext
 * @param service service
 * @param clsName clsName
 * @param scopeHolder scopeHolder
 * @return
 * @throws Exception
 */
@Override
public Object getServiceObject(MessageContext msgContext, Handler service, String clsName, IntHolder scopeHolder) throws Exception {
    HttpRequest request = (HttpRequest) msgContext.getProperty(AxisWsContainer.REQUEST);
    return request.getAttribute(WsConstants.POJO_INSTANCE);
}
 
Example #30
Source File: EjbRpcProvider.java    From tomee with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @param msgContext msgContext
 * @param service service
 * @param clsName clsName
 * @param scopeHolder scopeHolder
 * @return
 * @throws Exception
 */
@Override
public Object getServiceObject(MessageContext msgContext, Handler service, String clsName, IntHolder scopeHolder) throws Exception {
    return ejbDeployment;
}