Java Code Examples for org.apache.axis.MessageContext#setProperty()

The following examples show how to use org.apache.axis.MessageContext#setProperty() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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);
}