public void destroy() { TemplateMediator templateMediator = synapseEnv.getSynapseConfiguration().getSequenceTemplate(targetTemplate); if (templateMediator == null || templateMediator.isDynamic()) { synapseEnv.removeUnavailableArtifactRef(targetTemplate); } }
public void init(SynapseEnvironment se) { synapseEnv = se; TemplateMediator templateMediator = se.getSynapseConfiguration().getSequenceTemplate(targetTemplate); if (templateMediator == null || templateMediator.isDynamic()) { // undefined or dynamic templates are treated as unavailable // in the environment. // At the time of their initialization, these will be marked as available. se.addUnavailableArtifactRef(targetTemplate); } }
protected boolean injectMessage(InputStream in, String contentType) { try { org.apache.synapse.MessageContext msgCtx = createMessageContext(); if (log.isDebugEnabled()) { log.debug("Processed Custom inbound EP Message of Content-type : " + contentType); } MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx).getAxis2MessageContext(); // Determine the message builder to use Builder builder; if (contentType == null) { log.debug("No content type specified. Using SOAP builder."); builder = new SOAPBuilder(); } else { int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx); if (builder == null) { if (log.isDebugEnabled()) { log.debug("No message builder found for type '" + type + "'. Falling back to SOAP."); } builder = new SOAPBuilder(); } } OMElement documentElement = builder.processDocument(in, contentType, axis2MsgCtx); // Inject the message to the sequence. msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); if (injectingSeq == null || injectingSeq.equals("")) { log.error("Sequence name not specified. Sequence : " + injectingSeq); return false; } SequenceMediator seq = (SequenceMediator) synapseEnvironment.getSynapseConfiguration().getSequence(injectingSeq); if (seq != null) { if (log.isDebugEnabled()) { log.debug("injecting message to sequence : " + injectingSeq); } seq.setErrorHandler(onErrorSeq); if (!seq.isInitialized()) { seq.init(synapseEnvironment); } if (!synapseEnvironment.injectInbound(msgCtx, seq, sequential)) { return false; } } else { log.error("Sequence: " + injectingSeq + " not found"); } } catch (Exception e) { log.error("Error while processing the Custom Inbound EP Message."); } return true; }
public void destroy() { if (onCompleteSequence != null) { onCompleteSequence.destroy(); } else if (onCompleteSequenceRef != null) { SequenceMediator referredOnCompleteSeq = (SequenceMediator) synapseEnv.getSynapseConfiguration().getSequence(onCompleteSequenceRef); if (referredOnCompleteSeq == null || referredOnCompleteSeq.isDynamic()) { synapseEnv.removeUnavailableArtifactRef(onCompleteSequenceRef); } } }
public void init(SynapseEnvironment se) { synapseEnv = se; if (onCompleteSequence != null) { onCompleteSequence.init(se); } else if (onCompleteSequenceRef != null) { SequenceMediator referredOnCompleteSeq = (SequenceMediator) se.getSynapseConfiguration().getSequence(onCompleteSequenceRef); if (referredOnCompleteSeq == null || referredOnCompleteSeq.isDynamic()) { se.addUnavailableArtifactRef(onCompleteSequenceRef); } } }
public void init(SynapseEnvironment synapseEnvironment) { this.synapseEnv = synapseEnvironment; if (endpoint != null) { endpoint.init(synapseEnvironment); } if (blocking) { try { configCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem( DEFAULT_CLIENT_REPO, DEFAULT_AXIS2_XML); blockingMsgSender = new BlockingMsgSender(); blockingMsgSender.setConfigurationContext(configCtx); blockingMsgSender.init(); } catch (AxisFault axisFault) { String msg = "Error while initializing the Call mediator"; log.error(msg, axisFault); throw new SynapseException(msg, axisFault); } } else { synapseEnvironment.updateCallMediatorCount(true); } }
/** 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; }
/** This will be invoked by the schedular to inject the message in to the SynapseEnvironment */ public void execute() { log.debug("execute"); if (synapseEnvironment == null) { log.error("Synapse Environment not set"); return; } if (message == null) { log.error("message not set"); return; } if (to == null) { log.error("to address not set"); return; } MessageContext mc = synapseEnvironment.createMessageContext(); // AspectHelper.setGlobalAudit(mc); TODO mc.pushFaultHandler(new MediatorFaultHandler(mc.getFaultSequence())); mc.setTo(new EndpointReference(to)); if (format == null) { PayloadHelper.setXMLPayload(mc, message.cloneOMElement()); } else { try { if (SOAP11_FORMAT.equalsIgnoreCase(format)) { mc.setEnvelope(OMAbstractFactory.getSOAP11Factory().createSOAPEnvelope()); } else if (SOAP12_FORMAT.equalsIgnoreCase(format)) { mc.setEnvelope(OMAbstractFactory.getSOAP12Factory().createSOAPEnvelope()); } else if (POX_FORMAT.equalsIgnoreCase(format)) { mc.setDoingPOX(true); } else if (GET_FORMAT.equalsIgnoreCase(format)) { mc.setDoingGET(true); } PayloadHelper.setXMLPayload(mc, message.cloneOMElement()); } catch (AxisFault axisFault) { String msg = "Error in setting the message payload : " + message; log.error(msg, axisFault); throw new SynapseException(msg, axisFault); } } if (soapAction != null) { mc.setSoapAction(soapAction); } synapseEnvironment.injectMessage(mc); }
// TODO: Refactor this. need to be moved to somewhere else. This is not an util public static boolean injectMessage( MessageContext synCtx, SynapseEnvironment synapseEnvironment, String injectingSeq) { if (injectingSeq == null || injectingSeq.equals("")) { log.error("Sequence name not specified. Sequence : " + injectingSeq); return false; } SequenceMediator seq = (SequenceMediator) synapseEnvironment.getSynapseConfiguration().getSequence(injectingSeq); if (seq != null) { if (log.isDebugEnabled()) { log.debug("Injecting message to sequence : " + injectingSeq); } synapseEnvironment.injectAsync(synCtx, seq); return true; } else { log.error("Sequence: " + injectingSeq + " not found"); return false; } }
private boolean setMessageConsumer() { final String messageStore = messageProcessor.getMessageStoreName(); messageConsumer = synapseEnvironment.getSynapseConfiguration().getMessageStore(messageStore).getConsumer(); /* * Make sure to set the same message consumer in the message processor * since it is used by life-cycle management methods. Specially by the * deactivate method to cleanup the connection before the deactivation. */ return messageProcessor.setMessageConsumer(messageConsumer); }
public void destroy() { for (Target target : targets) { ManagedLifecycle seq = target.getSequence(); if (seq != null) { seq.destroy(); } else if (target.getSequenceRef() != null) { SequenceMediator targetSequence = (SequenceMediator) synapseEnv.getSynapseConfiguration().getSequence(target.getSequenceRef()); if (targetSequence == null || targetSequence.isDynamic()) { synapseEnv.removeUnavailableArtifactRef(target.getSequenceRef()); } } Endpoint endpoint = target.getEndpoint(); if (endpoint != null) { endpoint.destroy(); } } }
public void init(SynapseEnvironment se) { synapseEnv = se; for (Target target : targets) { ManagedLifecycle seq = target.getSequence(); if (seq != null) { seq.init(se); } else if (target.getSequenceRef() != null) { SequenceMediator targetSequence = (SequenceMediator) se.getSynapseConfiguration().getSequence(target.getSequenceRef()); if (targetSequence == null || targetSequence.isDynamic()) { se.addUnavailableArtifactRef(target.getSequenceRef()); } } Endpoint endpoint = target.getEndpoint(); if (endpoint != null) { endpoint.init(se); } } }
/** Destroys the Synapse Environment by undeploying all Axis2 services. */ public void destroySynapseEnvironment() { if (synapseEnvironment != null) { try { undeploySynapseService(); undeployProxyServices(); undeployEventSources(); } catch (AxisFault e) { handleFatal("Error while shutting down the Synapse environment", e); } synapseEnvironment.setInitialized(false); } }
/** * Setup synapse in axis2 environment and return the created instance. * * @return SynapseEnvironment instance */ public SynapseEnvironment createSynapseEnvironment() { try { deployMediationLibraryArtifacts(); deployMediatorExtensions(); deploySynapseService(); deployProxyServices(); deployEventSources(); // deployMediatorExtensions(); } catch (AxisFault axisFault) { log.fatal("Synapse startup failed...", axisFault); throw new SynapseException("Synapse startup failed", axisFault); } synapseEnvironment = new Axis2SynapseEnvironment( configurationContext, synapseConfiguration, serverContextInformation); MessageContextCreatorForAxis2.setSynEnv(synapseEnvironment); Parameter synapseEnvironmentParameter = new Parameter(SynapseConstants.SYNAPSE_ENV, synapseEnvironment); try { configurationContext.getAxisConfiguration().addParameter(synapseEnvironmentParameter); } catch (AxisFault e) { handleFatal( "Could not set parameter '" + SynapseConstants.SYNAPSE_ENV + "' to the Axis2 configuration : " + e.getMessage(), e); } synapseEnvironment.getTaskManager().init(taskDescriptionRepository, taskScheduler); synapseConfiguration.init(synapseEnvironment); synapseEnvironment.setInitialized(true); return synapseEnvironment; }
/** {@inheritDoc} */ public void endMaintenance() { log.info("Resuming transport listeners, senders and tasks from maintenance mode..."); // resume transport listeners and senders Axis2TransportHelper transportHelper = new Axis2TransportHelper(configurationContext); transportHelper.resumeListeners(); transportHelper.resumeSenders(); // resume tasks SynapseTaskManager synapseTaskManager = synapseEnvironment.getTaskManager(); if (synapseTaskManager.isInitialized()) { synapseTaskManager.resumeAll(); } log.info("Resumed normal operation from maintenance mode"); }
/** 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; }
/** {@inheritDoc} */ public void startMaintenance() { log.info("Putting transport listeners, senders and tasks into maintenance mode.."); // pause transport listeners and senders Axis2TransportHelper transportHelper = new Axis2TransportHelper(configurationContext); transportHelper.pauseListeners(); transportHelper.pauseSenders(); // put tasks on hold SynapseTaskManager synapseTaskManager = synapseEnvironment.getTaskManager(); if (synapseTaskManager.isInitialized()) { synapseTaskManager.pauseAll(); } log.info("Entered maintenance mode"); }
public void init(SynapseEnvironment se) { if (isPinnedServer( se.getServerContextInformation().getServerConfigurationInformation().getServerName())) { // If it is a pinned server we do not start the message processors. In that server. setActivated(false); } super.init(se); StdSchedulerFactory sf = null; try { sf = new StdSchedulerFactory(getSchedulerProperties(this.name)); if (quartzConfig != null && !"".equals(quartzConfig)) { if (logger.isDebugEnabled()) { logger.debug("Initiating a Scheduler with configuration : " + quartzConfig); } sf.initialize(quartzConfig); } } catch (SchedulerException e) { throw new SynapseException( "Error initiating scheduler factory " + sf + "with configuration loaded from " + quartzConfig, e); } try { scheduler = sf.getScheduler(); } catch (SchedulerException e) { throw new SynapseException( "Error getting a scheduler instance form scheduler" + " factory " + sf, e); } this.start(); if (!isActivated.get()) { deactivate(); } }
public static MessageContext createSynapseMessageContext( org.apache.axis2.context.MessageContext axis2mc, SynapseEnvironment se) { SynapseConfiguration configuration = se.getSynapseConfiguration(); return new Axis2MessageContext(axis2mc, configuration, se); }
public void destroy() { if (endpoint != null) { endpoint.destroy(); } synapseEnv.updateCallMediatorCount(false); }
/** Cleanup the axis2 environment and stop the synapse environment. */ public void stop() { try { // stop tasks SynapseTaskManager synapseTaskManager = synapseEnvironment.getTaskManager(); if (synapseTaskManager.isInitialized()) { synapseTaskManager.cleanup(); } EnterpriseBeanstalkManager manager = (EnterpriseBeanstalkManager) serverContextInformation.getProperty( EnterpriseBeanstalkConstants.BEANSTALK_MANAGER_PROP_NAME); if (manager != null) { manager.destroy(); } // stop the listener manager if (listenerManager != null) { listenerManager.stop(); } // detach the synapse handlers if (configurationContext != null) { List<Phase> inflowPhases = configurationContext.getAxisConfiguration().getInFlowPhases(); for (Phase inPhase : inflowPhases) { // we are interested about the Dispatch phase in the inflow if (PhaseMetadata.PHASE_DISPATCH.equals(inPhase.getPhaseName())) { List<HandlerDescription> synapseHandlers = new ArrayList<HandlerDescription>(); for (Handler handler : inPhase.getHandlers()) { if (SynapseDispatcher.NAME.equals(handler.getName()) || SynapseMustUnderstandHandler.NAME.equals(handler.getName())) { synapseHandlers.add(handler.getHandlerDesc()); } } for (HandlerDescription handlerMD : synapseHandlers) { inPhase.removeHandler(handlerMD); } } } } else { handleException( "Couldn't detach the Synapse handlers, " + "ConfigurationContext not found."); } // continue stopping the axis2 environment if we created it if (serverConfigurationInformation.isCreateNewInstance() && configurationContext != null && configurationContext.getAxisConfiguration() != null) { Map<String, AxisService> serviceMap = configurationContext.getAxisConfiguration().getServices(); for (AxisService svc : serviceMap.values()) { svc.setActive(false); } // stop all modules Map<String, AxisModule> moduleMap = configurationContext.getAxisConfiguration().getModules(); for (AxisModule mod : moduleMap.values()) { if (mod.getModule() != null && !"synapse".equals(mod.getName())) { mod.getModule().shutdown(configurationContext); } } } } catch (AxisFault e) { log.error("Error stopping the Axis2 Environment"); } }
/** Invoke the mediation logic for the passed message */ public boolean invoke(Object object, String name) throws SynapseException { Message msg = (Message) object; try { org.apache.synapse.MessageContext msgCtx = createMessageContext(); msgCtx.setProperty("inbound.endpoint.name", name); InboundEndpoint inboundEndpoint = msgCtx.getConfiguration().getInboundEndpoint(name); CustomLogSetter.getInstance().setLogAppender(inboundEndpoint.getArtifactContainerName()); String contentType = msg.getJMSType(); if (contentType == null || contentType.trim().equals("")) { String contentTypeProperty = jmsProperties.getProperty(JMSConstants.CONTENT_TYPE_PROPERTY); if (contentTypeProperty != null) { contentType = msg.getStringProperty(contentTypeProperty); } } else { msgCtx.setProperty(JMSConstants.JMS_MESSAGE_TYPE, contentType); } if (contentType == null || contentType.trim().equals("")) { contentType = jmsProperties.getProperty(JMSConstants.CONTENT_TYPE); } if (log.isDebugEnabled()) { log.debug("Processed JMS Message of Content-type : " + contentType); } MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx).getAxis2MessageContext(); // set the JMS Message ID as the Message ID of the MessageContext try { msgCtx.setMessageID(msg.getJMSMessageID()); String jmsCorrelationID = msg.getJMSCorrelationID(); if (jmsCorrelationID != null && !jmsCorrelationID.isEmpty()) { msgCtx.setProperty(JMSConstants.JMS_COORELATION_ID, jmsCorrelationID); } else { msgCtx.setProperty(JMSConstants.JMS_COORELATION_ID, msg.getJMSMessageID()); } } catch (JMSException ignore) { log.warn("Error getting the COORELATION ID from the message."); } // Handle dual channel Destination replyTo = msg.getJMSReplyTo(); if (replyTo != null) { msgCtx.setProperty(SynapseConstants.IS_INBOUND, true); // Create the cachedJMSConnectionFactory with the existing // connection CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory(jmsProperties, connection); String strUserName = jmsProperties.getProperty(JMSConstants.PARAM_JMS_USERNAME); String strPassword = jmsProperties.getProperty(JMSConstants.PARAM_JMS_PASSWORD); JMSReplySender jmsReplySender = new JMSReplySender(replyTo, cachedJMSConnectionFactory, strUserName, strPassword); msgCtx.setProperty( InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, jmsReplySender); } else if (replyDestination != null) { msgCtx.setProperty(SynapseConstants.IS_INBOUND, true); // Create the cachedJMSConnectionFactory with the existing // connection CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory(jmsProperties, connection); String strUserName = jmsProperties.getProperty(JMSConstants.PARAM_JMS_USERNAME); String strPassword = jmsProperties.getProperty(JMSConstants.PARAM_JMS_PASSWORD); JMSReplySender jmsReplySender = new JMSReplySender( replyDestination, cachedJMSConnectionFactory, strUserName, strPassword); msgCtx.setProperty( InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, jmsReplySender); } // Determine the message builder to use Builder builder; if (contentType == null) { log.debug("No content type specified. Using SOAP builder."); builder = new SOAPBuilder(); } else { int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx); if (builder == null) { if (log.isDebugEnabled()) { log.debug("No message builder found for type '" + type + "'. Falling back to SOAP."); } builder = new SOAPBuilder(); } } OMElement documentElement = null; // set the message payload to the message context if (msg instanceof TextMessage) { String message = ((TextMessage) msg).getText(); InputStream in = new AutoCloseInputStream(new ByteArrayInputStream(message.getBytes())); documentElement = builder.processDocument(in, contentType, axis2MsgCtx); } else if (msg instanceof BytesMessage) { if (builder instanceof DataSourceMessageBuilder) { documentElement = ((DataSourceMessageBuilder) builder) .processDocument( new BytesMessageDataSource((BytesMessage) msg), contentType, axis2MsgCtx); } else { documentElement = builder.processDocument( new BytesMessageInputStream((BytesMessage) msg), contentType, axis2MsgCtx); } } else if (msg instanceof MapMessage) { documentElement = convertJMSMapToXML((MapMessage) msg); } // Inject the message to the sequence. msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); if (injectingSeq == null || injectingSeq.equals("")) { log.error("Sequence name not specified. Sequence : " + injectingSeq); return false; } SequenceMediator seq = (SequenceMediator) synapseEnvironment.getSynapseConfiguration().getSequence(injectingSeq); if (seq != null) { if (log.isDebugEnabled()) { log.debug("injecting message to sequence : " + injectingSeq); } seq.setErrorHandler(onErrorSeq); if (!synapseEnvironment.injectInbound(msgCtx, seq, sequential)) { return false; } } else { log.error("Sequence: " + injectingSeq + " not found"); } Object o = msgCtx.getProperty(JMSConstants.SET_ROLLBACK_ONLY); if (o != null) { if ((o instanceof Boolean && ((Boolean) o)) || (o instanceof String && Boolean.valueOf((String) o))) { return false; } } } catch (SynapseException se) { throw se; } catch (Exception e) { log.error("Error while processing the JMS Message", e); throw new SynapseException("Error while processing the JMS Message", e); } return true; }
/** * Waits until it is safe to stop or the the specified end time has been reached. A delay of * <code>waitIntervalMillis</code> milliseconds is used between each subsequent check. If the * state "safeToStop" is reached before the specified <code>endTime</code>, the return value is * true. * * @param waitIntervalMillis the pause time (delay) in milliseconds between subsequent checks * @param endTime the time until which the checks need to finish successfully * @return true, if a safe state is reached before the specified <code>endTime</code>, otherwise * false (forceful stop required) */ public boolean waitUntilSafeToStop(long waitIntervalMillis, long endTime) { boolean safeToStop = false; boolean forcefulStop = false; Axis2TransportHelper transportHelper = new Axis2TransportHelper(configurationContext); // wait until it is safe to shutdown (listeners and tasks are idle, no callbacks) while (!safeToStop && !forcefulStop) { int pendingListenerThreads = transportHelper.getPendingListenerThreadCount(); if (pendingListenerThreads > 0) { log.info( new StringBuilder("Waiting for: ") .append(pendingListenerThreads) .append(" listener threads to complete") .toString()); } int pendingSenderThreads = transportHelper.getPendingSenderThreadCount(); if (pendingSenderThreads > 0) { log.info( new StringBuilder("Waiting for: ") .append(pendingSenderThreads) .append(" listener threads to complete") .toString()); } int activeConnections = transportHelper.getActiveConnectionsCount(); if (activeConnections > 0) { log.info("Waiting for: " + activeConnections + " active connections to be closed.."); } int pendingTransportThreads = pendingListenerThreads + pendingSenderThreads; int pendingCallbacks = serverContextInformation.getCallbackCount(); if (pendingCallbacks > 0) { log.info("Waiting for: " + pendingCallbacks + " callbacks/replies.."); } int runningTasks = 0; SynapseTaskManager synapseTaskManager = synapseEnvironment.getTaskManager(); if (synapseTaskManager.isInitialized()) { runningTasks = synapseTaskManager.getTaskScheduler().getRunningTaskCount(); if (runningTasks > 0) { log.info("Waiting for : " + runningTasks + " tasks to complete.."); } } // it is safe to stop if all used listener threads, callbacks and tasks are zero safeToStop = ((pendingTransportThreads + pendingCallbacks + runningTasks) == 0); if (safeToStop) { log.info("All transport threads and tasks are idle and no pending callbacks.."); } else { if (System.currentTimeMillis() < endTime) { log.info( new StringBuilder("Waiting for a maximum of another ") .append((endTime - System.currentTimeMillis()) / 1000) .append(" seconds until transport threads and tasks become idle, ") .append("active connections to get closed,") .append(" and callbacks to be completed..") .toString()); try { Thread.sleep(waitIntervalMillis); } catch (InterruptedException ignore) { // nothing to do here } } else { // maximum time to wait is over, do a forceful stop forcefulStop = true; } } } return !forcefulStop; }