/** * This is is a workaround for axis2 RestUtils behaviour Based on an internal property and the * http method, we set the message type * * @param originalInMsgCtx IN message * @param axisOutMsgCtx Out message */ private static void processWSDL2RESTRequestMessageType( MessageContext originalInMsgCtx, MessageContext axisOutMsgCtx) { // TODO - this is a workaround for axis2 RestUtils behaviour Object restContentType = originalInMsgCtx.getProperty(NhttpConstants.REST_REQUEST_CONTENT_TYPE); if (restContentType == null) { String httpMethod = (String) originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD); if (Constants.Configuration.HTTP_METHOD_GET.equals(httpMethod) || Constants.Configuration.HTTP_METHOD_DELETE.equals(httpMethod)) { restContentType = HTTPConstants.MEDIA_TYPE_X_WWW_FORM; } } // Removed ESB 4.7.0 PPT 2013-06-28 // if (restContentType != null && restContentType instanceof String) { // String contentType = TransportUtils.getContentType((String) restContentType, // originalInMsgCtx); // axisOutMsgCtx.setProperty( // org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, contentType); // originalInMsgCtx.setProperty( // org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, contentType); // } }
/** * Invokes the bussiness logic invocation on the service implementation class * * @param msgContext the incoming message context * @param newmsgContext the response message context * @throws AxisFault on invalid method (wrong signature) or behaviour (return null) */ public void invokeBusinessLogic(MessageContext msgContext, MessageContext newmsgContext) throws AxisFault { try { // get the implementation class for the Web Service Object obj = getTheImplementationObject(msgContext); // find the WebService method Class implClass = obj.getClass(); AxisOperation opDesc = msgContext.getAxisOperation(); Method method = findOperation(opDesc, implClass); if (method == null) { throw new AxisFault( Messages.getMessage("methodDoesNotExistInOut", opDesc.getName().toString())); } OMElement result = (OMElement) method.invoke( obj, new Object[] {msgContext.getEnvelope().getBody().getFirstElement()}); SOAPFactory fac = getSOAPFactory(msgContext); SOAPEnvelope envelope = fac.getDefaultEnvelope(); if (result != null) { envelope.getBody().addChild(result); } newmsgContext.setEnvelope(envelope); } catch (Exception e) { throw AxisFault.makeFault(e); } }
/** {@inheritDoc} */ public InvocationResponse invoke(MessageContext msgContext) throws AxisFault { final XdsWriteAuthzManager xdsWriteAuthzManager = (XdsWriteAuthzManager) applicationContext.getBean("xdsWriteAuthzManager"); boolean hasAccess = false; if (PROVIDE_AND_REGISETR_DOCUMENT_SET_B.equals(msgContext.getWSAAction())) { LOG.debug("ACTION INVOKED-------- ::: " + msgContext.getWSAAction()); final String subjectDN = getSubjectDN(msgContext); LOG.debug("SubjectDN -------- ::: " + subjectDN); try { hasAccess = xdsWriteAuthzManager.checkStoreWrite(subjectDN); } catch (AuthzProvisioningException e) { throw new AxisFault("Error while checking access", e); // CHECKSTYLE:OFF } catch (Exception e) { // CHECKSTYLE:ON throw new AxisFault("Error while checking access", e); } if (!hasAccess) { throw new AxisFault("Permission denied"); } } return InvocationResponse.CONTINUE; }
/** * Whether the original request received by the synapse is REST * * @param originalInMsgCtx request message * @return <code>true</code> if the request was a REST request */ private static boolean isRequestRest(MessageContext originalInMsgCtx) { boolean isRestRequest = originalInMsgCtx.getProperty(NhttpConstants.REST_REQUEST_CONTENT_TYPE) != null; if (!isRestRequest) { String httpMethod = (String) originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD); isRestRequest = Constants.Configuration.HTTP_METHOD_GET.equals(httpMethod) || Constants.Configuration.HTTP_METHOD_DELETE.equals(httpMethod) || Constants.Configuration.HTTP_METHOD_PUT.equals(httpMethod) || RESTConstants.METHOD_OPTIONS.equals(httpMethod) || Constants.Configuration.HTTP_METHOD_HEAD.equals(httpMethod); if (!isRestRequest) { isRestRequest = Constants.Configuration.HTTP_METHOD_POST.equals(httpMethod) && HTTPTransportUtils.isRESTRequest( String.valueOf( originalInMsgCtx.getProperty(Constants.Configuration.MESSAGE_TYPE))); if (!isRestRequest) { isRestRequest = (String.valueOf(originalInMsgCtx.getProperty(Constants.Configuration.MESSAGE_TYPE)) .equals(HTTPConstants.MEDIA_TYPE_TEXT_XML) && originalInMsgCtx.getSoapAction() == null); } } } return isRestRequest; }
/** same as OutInAxisOperationClient */ public void addMessageContext(MessageContext mc) throws AxisFault { mc.setServiceContext(sc); if (mc.getMessageID() == null) { setMessageID(mc); } axisOp.registerOperationContext(mc, oc); }
/* * (non-Javadoc) * @see org.apache.axis2.jaxws.core.controller.InvocationController#prepareRequest(org.apache.axis2.jaxws.core.MessageContext) */ protected void prepareRequest(MessageContext requestMsgCtx) { try { if (requestMsgCtx == null) { // throw an exception } org.apache.axis2.context.MessageContext axisRequestMsgCtx = requestMsgCtx.getAxisMessageContext(); // The MessageContext will contain a Message object with the // contents that need to be sent. We need to get those contents // in a form that Axis2 can consume them, an AXIOM SOAPEnvelope. MessageUtils.putMessageOnMessageContext( requestMsgCtx.getMessage(), // JAX-WS Message axisRequestMsgCtx // Axis 2 MessageContext ); if (log.isDebugEnabled()) { log.debug("Properties: " + axisRequestMsgCtx.getProperties().toString()); } } catch (WebServiceException e) { throw ExceptionFactory.makeWebServiceException(Messages.getMessage("prepareRequestFail")); } catch (AxisFault e) { throw ExceptionFactory.makeWebServiceException(Messages.getMessage("prepareRequestFail"), e); } }
private String getRedirectionReadyFullRequestPath(MessageContext messageContext) { String fullResourceURL = (String) messageContext.getProperty(RESTConstants.REST_FULL_REQUEST_PATH); // If the request has come though the default Synapse API (without versioning) remove the // version part of the URL. org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); Map<String, Object> headers = (Map<String, Object>) axis2MessageContext.getProperty( org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); String hasRequestedThoughDefaultVersion = (String) headers.get(AppMConstants.GATEWAY_DEFAULT_VERSION_INDICATION_HEADER_NAME); if (hasRequestedThoughDefaultVersion != null && Boolean.parseBoolean(hasRequestedThoughDefaultVersion)) { String webAppVersion = (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION); return fullResourceURL.replaceFirst("/" + webAppVersion, ""); } return fullResourceURL; }
private void sendUsingOutputStream(MessageContext msgContext) throws AxisFault { OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = MessageFormatterDecoratorFactory.createMessageFormatterDecorator(msgContext); OutputStream out = (OutputStream) msgContext.getProperty(MessageContext.TRANSPORT_OUT); if (msgContext.isServerSide()) { OutTransportInfo transportInfo = (OutTransportInfo) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO); if (transportInfo != null) { transportInfo.setContentType( messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction())); } else { throw new AxisFault(Constants.OUT_TRANSPORT_INFO + " has not been set"); } } try { messageFormatter.writeTo(msgContext, format, out, false); out.close(); } catch (IOException e) { handleException("IO Error sending response message", e); } }
/** Create the initial message context for the file */ private org.apache.synapse.MessageContext createMessageContext() { org.apache.synapse.MessageContext msgCtx = synapseEnvironment.createMessageContext(); MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx).getAxis2MessageContext(); axis2MsgCtx.setServerSide(true); axis2MsgCtx.setMessageID(UUIDGenerator.getUUID()); return msgCtx; }
/* * (non-Javadoc) * @see org.apache.axis2.jaxws.core.controller.InvocationController#invokeAsync(org.apache.axis2.jaxws.core.InvocationContext) */ public Response doInvokeAsync(MessageContext request) { // We need the qname of the operation being invoked to know which // AxisOperation the OperationClient should be based on. // Note that the OperationDesc is only set through use of the Proxy. Dispatch // clients do not use operations, so the operationDesc will be null. In this // case an anonymous AxisService with anoymouns AxisOperations for the supported // MEPs will be created; and it is that anonymous operation name which needs to // be specified QName operationName = getOperationNameToUse(request, ServiceClient.ANON_OUT_IN_OP); // TODO: Will the ServiceClient stick around on the InvocationContext // or will we need some other mechanism of creating this? // Try to create an OperationClient from the passed in ServiceClient InvocationContext ic = request.getInvocationContext(); ServiceClient svcClient = ic.getServiceClient(); OperationClient opClient = createOperationClient(svcClient, operationName); initOperationClient(opClient, request); // Setup the client so that it knows whether the underlying call to // Axis2 knows whether or not to start a listening port for an // asynchronous response. Boolean useAsyncMep = (Boolean) request.getProperty(Constants.USE_ASYNC_MEP); if ((useAsyncMep != null && useAsyncMep.booleanValue()) || opClient.getOptions().isUseSeparateListener()) { configureAsyncListener(opClient); } else { if (log.isDebugEnabled()) { log.debug( "Asynchronous message exchange not enabled. The invocation will be synchronous."); } } AsyncResponse resp = ic.getAsyncResponseListener(); PollingFuture pf = new PollingFuture(ic); opClient.setCallback(pf); org.apache.axis2.context.MessageContext axisRequestMsgCtx = request.getAxisMessageContext(); try { execute(opClient, false, axisRequestMsgCtx); } catch (AxisFault af) { if (log.isDebugEnabled()) { log.debug( axisRequestMsgCtx.getLogIDString() + " AxisFault received from client: " + af.getMessage()); } /* * Save the exception on the callback. The client will learn about the error when they try to * retrieve the async results via the Response.get(). "Errors that occur during the invocation * are reported via an exception when the client attempts to retrieve the results of the operation." * -- JAXWS 4.3.3 */ pf.onError(af); } return resp; }
public static String sendSOAP( EndpointReference soapEPR, String requestString, String action, String operation) throws Exception { ServiceClient sender = PmServiceClient.getServiceClient(); OperationClient operationClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP); // creating message context MessageContext outMsgCtx = new MessageContext(); // assigning message context's option object into instance variable Options opts = outMsgCtx.getOptions(); // setting properties into option log.debug(soapEPR); opts.setTo(soapEPR); opts.setAction(action); opts.setTimeOutInMilliSeconds(180000); log.debug(requestString); SOAPEnvelope envelope = null; try { SOAPFactory fac = OMAbstractFactory.getSOAP11Factory(); envelope = fac.getDefaultEnvelope(); OMNamespace omNs = fac.createOMNamespace( "http://rpdr.partners.org/", //$NON-NLS-1$ "rpdr"); //$NON-NLS-1$ // creating the SOAP payload OMElement method = fac.createOMElement(operation, omNs); OMElement value = fac.createOMElement("RequestXmlString", omNs); // $NON-NLS-1$ value.setText(requestString); method.addChild(value); envelope.getBody().addChild(method); } catch (FactoryConfigurationError e) { log.error(e.getMessage()); throw new Exception(e); } outMsgCtx.setEnvelope(envelope); operationClient.addMessageContext(outMsgCtx); operationClient.execute(true); MessageContext inMsgtCtx = operationClient.getMessageContext("In"); // $NON-NLS-1$ SOAPEnvelope responseEnv = inMsgtCtx.getEnvelope(); OMElement soapResponse = responseEnv.getBody().getFirstElement(); // System.out.println("Sresponse: "+ soapResponse.toString()); OMElement soapResult = soapResponse.getFirstElement(); // System.out.println("Sresult: "+ soapResult.toString()); String i2b2Response = soapResult.getText(); log.debug(i2b2Response); return i2b2Response; }
public void invokeBusinessLogic(org.apache.axis2.context.MessageContext msgContext) throws org.apache.axis2.AxisFault { try { // get the implementation class for the Web Service Object obj = getTheImplementationObject(msgContext); MultitenancyThrottlingServiceSkeletonInterface skel = (MultitenancyThrottlingServiceSkeletonInterface) obj; // Out Envelop org.apache.axiom.soap.SOAPEnvelope envelope = null; // Find the axisOperation that has been set by the Dispatch phase. org.apache.axis2.description.AxisOperation op = msgContext.getOperationContext().getAxisOperation(); if (op == null) { throw new org.apache.axis2.AxisFault( "Operation is not located, if this is doclit style the SOAP-ACTION should specified via the SOAP Action to use the RawXMLProvider"); } java.lang.String methodName; if ((op.getName() != null) && ((methodName = org.apache.axis2.util.JavaUtils.xmlNameToJavaIdentifier( op.getName().getLocalPart())) != null)) { if ("executeThrottlingRules".equals(methodName)) { // doc style org.wso2.carbon.throttling.manager.services.ExecuteThrottlingRules wrappedParam = (org.wso2.carbon.throttling.manager.services.ExecuteThrottlingRules) fromOM( msgContext.getEnvelope().getBody().getFirstElement(), org.wso2.carbon.throttling.manager.services.ExecuteThrottlingRules.class, getEnvelopeNamespaces(msgContext.getEnvelope())); skel.executeThrottlingRules(wrappedParam); envelope = getSOAPFactory(msgContext).getDefaultEnvelope(); } else { throw new java.lang.RuntimeException("method not found"); } } } catch (MultitenancyThrottlingServiceExceptionException e) { msgContext.setProperty( org.apache.axis2.Constants.FAULT_NAME, "MultitenancyThrottlingServiceException"); org.apache.axis2.AxisFault f = createAxisFault(e); if (e.getFaultMessage() != null) { f.setDetail(toOM(e.getFaultMessage(), false)); } throw f; } catch (java.lang.Exception e) { throw org.apache.axis2.AxisFault.makeFault(e); } }
// This is copied from PropertyMediator, required to change Content-Type private void handleSpecialProperties( Object resultValue, org.apache.axis2.context.MessageContext axis2MessageCtx) { axis2MessageCtx.setProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE, resultValue); Object o = axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); Map headers = (Map) o; if (headers != null) { headers.remove(HTTP.CONTENT_TYPE); headers.put(HTTP.CONTENT_TYPE, resultValue); } }
public boolean unregister(String domain, String subDomain, String hostName) throws CartridgeAgentException { MessageContext messageContext = MessageContext.getCurrentMessageContext(); ConfigurationContext configurationContext = messageContext.getConfigurationContext(); ClusteringClient clusteringClient = (ClusteringClient) configurationContext.getProperty(CartridgeAgentConstants.CLUSTERING_CLIENT); clusteringClient.removeClusterDomain(domain, subDomain, hostName, configurationContext); return true; }
private void addTransportHeader( MessageContext messageContext, String headerName, String headerValue) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); Map<String, Object> headers = (Map<String, Object>) axis2MessageContext.getProperty( org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); headers.put(headerName, headerValue); messageContext.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headers); }
/** {@inheritDoc} */ public InvocationResponse invoke(MessageContext messageContext) throws AxisFault { if (log.isDebugEnabled()) { log.debug( "Starting Activation Handler invocation. Incoming Message: " + messageContext.getEnvelope().toString()); } AxisService service = messageContext.getAxisService(); int tenantId = getTenantId(messageContext); if (service != null && "ActivationService".equals(service.getName())) { log.debug("Granted access to the Activation Service"); if (tenantId > 0) { TenantAxisUtils.getTenantAxisConfiguration( getTenantDomain(), messageContext.getConfigurationContext()); log.debug("Loaded Tenant Configuration"); } return InvocationResponse.CONTINUE; } if (tenantId == MultitenantConstants.SUPER_TENANT_ID) { log.debug("Granted access for super tenant"); return InvocationResponse.CONTINUE; } if (ActivationManager.activationRecorded(tenantId)) { if (ActivationManager.getActivation(tenantId)) { TenantAxisUtils.getTenantAxisConfiguration( getTenantDomain(), messageContext.getConfigurationContext()); log.debug("Loaded Tenant Configuration"); return InvocationResponse.CONTINUE; } else { if (log.isWarnEnabled()) { String serviceName = Util.getServiceName(); log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId); } return InvocationResponse.ABORT; } } String serviceName = Util.getServiceName(); try { if (CloudServicesUtil.isCloudServiceActive(serviceName, tenantId)) { log.debug("Successful attempt to access " + serviceName + " by tenant " + tenantId); ActivationManager.setActivation(tenantId, true); TenantAxisUtils.getTenantAxisConfiguration( getTenantDomain(), messageContext.getConfigurationContext()); log.debug("Loaded Tenant Configuration"); return InvocationResponse.CONTINUE; } } catch (Exception e) { throw new AxisFault("Failed to determine Activation status.", e); } log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId); ActivationManager.setActivation(tenantId, false); return InvocationResponse.ABORT; }
/** * Remove unwanted headers from the http response of outgoing request. These are headers which * should be dictated by the transport and not the user. We remove these as these may get copied * from the request messages * * @param msgContext the Axis2 Message context from which these headers should be removed */ private void removeUnwantedHeaders(MessageContext msgContext) { Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); Map excessHeaders = (Map) msgContext.getProperty(NhttpConstants.EXCESS_TRANSPORT_HEADERS); if (transportHeaders != null && !transportHeaders.isEmpty()) { removeUnwantedHeadersFromHeaderMap(transportHeaders, cfg); } if (excessHeaders != null && !excessHeaders.isEmpty()) { removeUnwantedHeadersFromHeaderMap(excessHeaders, cfg); } }
protected void setSessionID(MessageContext axis2MessageContext, String value) { if (value == null) { return; } Map map = (Map) axis2MessageContext.getProperty(HTTPConstants.HTTP_HEADERS); if (map == null) { map = new HashMap(); axis2MessageContext.setProperty(HTTPConstants.HTTP_HEADERS, map); } map.put(COOKIE, value); }
public ResponseToken process(RequestToken request) throws TrustException { MessageContext context = MessageContext.getCurrentMessageContext(); SAMLPassiveTokenIssuer issuer = null; WSHandlerResult handlerResults = null; WSSecurityEngineResult engineResult = null; WSUsernameTokenPrincipal principal = null; Vector<WSSecurityEngineResult> wsResults = null; ResponseToken reponseToken = null; Vector<WSHandlerResult> handlerResultsVector = null; OMElement rstr = null; try { if (request.getAttributes() == null || request.getAttributes().trim().length() == 0) { throw new TrustException("attributesMissing"); } principal = new WSUsernameTokenPrincipal(request.getUserName(), false); engineResult = new WSSecurityEngineResult(WSConstants.UT, principal, null, null, null); wsResults = new Vector<WSSecurityEngineResult>(); wsResults.add(engineResult); handlerResults = new WSHandlerResult("", wsResults); handlerResultsVector = new Vector<WSHandlerResult>(); handlerResultsVector.add(handlerResults); MessageContext.getCurrentMessageContext() .setProperty(WSHandlerConstants.RECV_RESULTS, handlerResultsVector); MessageContext.getCurrentMessageContext() .setProperty( RahasConstants.PASSIVE_STS_RST, getRST(request.getRealm(), request.getAttributes(), request.getDialect())); rahasData = new RahasData(context); issuer = new SAMLPassiveTokenIssuer(); issuer.setAudienceRestrictionCondition(request.getRealm()); issuer.setConfig( getSAMLTokenIssuerConfig( MessageContext.getCurrentMessageContext().getAxisService(), true)); rstr = issuer.issuePassiveRSTR(rahasData); reponseToken = new ResponseToken(); reponseToken.setResults(rstr.toStringWithConsume()); } catch (Exception e) { throw new TrustException("errorWhileProcessingAttributeRequest", e); } return reponseToken; }
public static void transferFile(File file, String destinationFile) throws Exception { Options options = new Options(); options.setTo(targetEPR); options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); // Increase the time out when sending large attachments options.setTimeOutInMilliSeconds(10000); options.setTo(targetEPR); options.setAction("urn:uploadFile"); // assume the use runs this sample at // <axis2home>/samples/soapwithattachments/ dir ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem( "../../repository", null); ServiceClient sender = new ServiceClient(configContext, null); sender.setOptions(options); OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP); MessageContext mc = new MessageContext(); FileDataSource fileDataSource = new FileDataSource(file); // Create a dataHandler using the fileDataSource. Any implementation of // javax.activation.DataSource interface can fit here. DataHandler dataHandler = new DataHandler(fileDataSource); String attachmentID = mc.addAttachment(dataHandler); SOAPFactory fac = OMAbstractFactory.getSOAP11Factory(); SOAPEnvelope env = fac.getDefaultEnvelope(); OMNamespace omNs = fac.createOMNamespace("http://service.soapwithattachments.sample", "swa"); OMElement uploadFile = fac.createOMElement("uploadFile", omNs); OMElement nameEle = fac.createOMElement("name", omNs); nameEle.setText(destinationFile); OMElement idEle = fac.createOMElement("attchmentID", omNs); idEle.setText(attachmentID); uploadFile.addChild(nameEle); uploadFile.addChild(idEle); env.getBody().addChild(uploadFile); mc.setEnvelope(env); mepClient.addMessageContext(mc); mepClient.execute(true); MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); SOAPBody body = response.getEnvelope().getBody(); OMElement element = body.getFirstElement() .getFirstChildWithName( new QName("http://service.soapwithattachments.sample", "return")); System.out.println(element.getText()); }
private String getHostHeader(org.apache.axis2.context.MessageContext msgCtx) { Map transportHeaders = (Map) msgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); String hostHeader = null; if (transportHeaders != null) { hostHeader = (String) transportHeaders.get(HTTP.TARGET_HOST); } if (hostHeader == null) { hostHeader = (String) msgCtx.getProperty(NhttpConstants.SERVICE_PREFIX); } return hostHeader; }
private static SOAPMessageContext getSOAPMessageContext(MessageContext jaxwsMessageContext) { org.apache.axis2.context.MessageContext msgContext = jaxwsMessageContext.getAxisMessageContext(); ServiceContext serviceContext = msgContext.getServiceContext(); SOAPMessageContext soapMessageContext = null; if (serviceContext != null) { WebServiceContext wsc = (WebServiceContext) serviceContext.getProperty(EndpointLifecycleManagerImpl.WEBSERVICE_MESSAGE_CONTEXT); if (wsc != null) { soapMessageContext = (SOAPMessageContext) wsc.getMessageContext(); } } return soapMessageContext; }
public void receive(org.apache.axis2.context.MessageContext mc) throws AxisFault { MessageContext synCtx = MessageContextCreatorForAxis2.getSynapseMessageContext(mc); StatisticsReporter.reportForComponent( synCtx, AspectConfigurationDetectionStrategy.getAspectConfiguration(synCtx), ComponentType.PROXYSERVICE); boolean traceOn = synCtx.getMainSequence().getTraceState() == SynapseConstants.TRACING_ON; boolean traceOrDebugOn = traceOn || log.isDebugEnabled(); if (traceOrDebugOn) { traceOrDebug(traceOn, "Synapse received a new message for message mediation..."); traceOrDebug( traceOn, "Received To: " + (mc.getTo() != null ? mc.getTo().getAddress() : "null")); traceOrDebug( traceOn, "SOAPAction: " + (mc.getSoapAction() != null ? mc.getSoapAction() : "null")); traceOrDebug( traceOn, "WSA-Action: " + (mc.getWSAAction() != null ? mc.getWSAAction() : "null")); if (traceOn && trace.isTraceEnabled()) { String[] cids = mc.getAttachmentMap().getAllContentIDs(); if (cids != null && cids.length > 0) { for (String cid : cids) { trace.trace("Attachment : " + cid); } } trace.trace("Envelope : " + mc.getEnvelope()); } } // get service log for this message and attach to the message context Log serviceLog = LogFactory.getLog( SynapseConstants.SERVICE_LOGGER_PREFIX + SynapseConstants.SYNAPSE_SERVICE_NAME); ((Axis2MessageContext) synCtx).setServiceLog(serviceLog); try { // invoke synapse message mediation through the main sequence synCtx.getEnvironment().injectMessage(synCtx); } catch (SynapseException syne) { if (!synCtx.getFaultStack().isEmpty()) { warn(traceOn, "Executing fault handler due to exception encountered", synCtx); ((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne); } else { warn( traceOn, "Exception encountered but no fault handler found - " + "message dropped", synCtx); } } finally { StatisticsReporter.endReportForAllOnRequestProcessed(synCtx); } }
private boolean isAckRequired() { // This condition is a bit complex but cannot simplify any further. if (msgContext != null) { if (msgContext.getOperationContext() != null && (!msgContext.getOperationContext().getAxisOperation().isControlOperation() || msgContext.isPropertyTrue(NhttpConstants.FORCE_SC_ACCEPTED))) { return true; } else if (msgContext.isPropertyTrue("NIO-ACK-Requested", false)) { return true; } } return false; }
private void processEntityEnclosingMethod() { try { Header contentType = request.getFirstHeader(HTTP.CONTENT_TYPE); String contentTypeStr = contentType != null ? contentType.getValue() : inferContentType(); String charSetEncoding = BuilderUtil.getCharSetEncoding(contentTypeStr); msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEncoding); if (HTTPTransportUtils.isRESTRequest(contentTypeStr) || isRest(contentTypeStr)) { RESTUtil.processPOSTRequest( msgContext, is, os, request.getRequestLine().getUri(), contentType, isRestDispatching); } else { Header soapAction = request.getFirstHeader(SOAPACTION); HTTPTransportUtils.processHTTPPostRequest( msgContext, is, os, contentTypeStr, (soapAction != null ? soapAction.getValue() : null), request.getRequestLine().getUri()); } } catch (Exception e) { handleException("Error processing POST request ", e); } }
/** Create the initial message context for the file */ private org.apache.synapse.MessageContext createMessageContext() { org.apache.synapse.MessageContext msgCtx = synapseEnvironment.createMessageContext(); // Need to set this to build the message msgCtx.setProperty(SynapseConstants.INBOUND_JMS_PROTOCOL, true); MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx).getAxis2MessageContext(); axis2MsgCtx.setServerSide(true); axis2MsgCtx.setMessageID(UUIDGenerator.getUUID()); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); axis2MsgCtx.setProperty(MultitenantConstants.TENANT_DOMAIN, carbonContext.getTenantDomain()); // There is a discrepency in what I thought, Axis2 spawns a nes threads // to // send a message is this is TRUE - and I want it to be the other way msgCtx.setProperty(MessageContext.CLIENT_API_NON_BLOCKING, true); return msgCtx; }
private int getTenantId(MessageContext messageContext) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); int tenantId = carbonContext.getTenantId(); if (tenantId > -1 || tenantId == MultitenantConstants.SUPER_TENANT_ID) { return tenantId; } String domain = carbonContext.getTenantDomain(); if (domain == null) { SOAPBody soapBody = messageContext.getEnvelope().getBody(); if (soapBody != null && soapBody.getFirstElement() != null) { OMElement usernameElem = soapBody .getFirstElement() .getFirstChildWithName( new QName( ServerConstants.AUTHENTICATION_SERVICE_NS, ServerConstants.AUTHENTICATION_SERVICE_USERNAME)); if (usernameElem != null) { String userName = usernameElem.getText(); domain = MultitenantUtils.getTenantDomain(userName); } } } if (domain != null) { try { tenantId = Util.getRealmService().getTenantManager().getTenantId(domain); } catch (org.wso2.carbon.user.api.UserStoreException e) { log.error("An error occurred while obtaining the tenant id.", e); } } return tenantId; }
/** * Method to obtain a list of paths having resources of the given media type. * * @param registry the registry instance to run query on. * @param mediaType the media type. * @return an array of resource paths. * @throws RegistryException if the operation failed. */ public static String[] getResultPaths(Registry registry, String mediaType) throws RegistryException { String[] result; String[] paginatedResult; try { Map<String, String> parameter = new HashMap<String, String>(); parameter.put("1", mediaType); parameter.put( "query", "SELECT DISTINCT REG_PATH_ID, REG_NAME FROM REG_RESOURCE WHERE REG_MEDIA_TYPE=?"); result = (String[]) registry.executeQuery(null, parameter).getContent(); if (result == null || result.length == 0) { return new String[0]; } result = removeMountPaths(result, registry); MessageContext messageContext = MessageContext.getCurrentMessageContext(); if (PaginationUtils.isPaginationAnnotationFound("getPaginatedGovernanceArtifacts") && ((messageContext != null && PaginationUtils.isPaginationHeadersExist(messageContext)) || PaginationContext.getInstance() != null)) { int rowCount = result.length; PaginationContext paginationContext; try { if (messageContext != null) { PaginationUtils.setRowCount(messageContext, Integer.toString(rowCount)); paginationContext = PaginationUtils.initPaginationContext(messageContext); } else { paginationContext = PaginationContext.getInstance(); } int start = paginationContext.getStart(); int count = paginationContext.getCount(); int startIndex; if (start == 1) { startIndex = 0; } else { startIndex = start; } if (rowCount < start + count) { paginatedResult = new String[rowCount - startIndex]; System.arraycopy(result, startIndex, paginatedResult, 0, (rowCount - startIndex)); } else { paginatedResult = new String[count]; System.arraycopy(result, startIndex, paginatedResult, 0, count); } return paginatedResult; } finally { PaginationContext.destroy(); } } } catch (RegistryException e) { String msg = "Error in getting the result for media type: " + mediaType + "."; log.error(msg, e); throw new RegistryException(msg, e); } return result; }
/** * Adding ws-Coordination context to soap request. * * @param msgCtx MessageContext * @param messageID UUID as a WS-Coordination identifier * @param registrationService URL of the ws-coordination registration service. */ public void addCoordinationContext( MessageContext msgCtx, String messageID, String registrationService) { SOAPHeader header = msgCtx.getEnvelope().getHeader(); EndpointReference epr = new EndpointReference(); epr.setAddress(registrationService); CoordinationContext context = new HumanTaskCoordinationContextImpl(messageID, epr); header.addChild(context.toOM()); }
@Override public InvocationResponse invoke(MessageContext messageContext) throws AxisFault { // get the counter property from the configuration context ConfigurationContext configurationContext = messageContext.getConfigurationContext(); Integer count = (Integer) configurationContext.getProperty(OUTGOING_MESSAGE_COUNT_KEY); // increment the counter count = Integer.valueOf(count.intValue() + 1 + ""); // set the new count back to the configuration context configurationContext.setProperty(OUTGOING_MESSAGE_COUNT_KEY, count); // print it out logger.info("The outgoing message count is now " + count); logger.info(messageContext.getEnvelope().toString()); return InvocationResponse.CONTINUE; }