/** @return Returns the promptMessage. */ public String getPromptMessage() { if (StringUtils.isNotBlank(resourceBundle) && StringUtils.isNotBlank(promptMessageCode)) { return StdioMessageFactory.getString(resourceBundle, promptMessageCode); } return promptMessage; }
/** * This is something of a hack. Velocity loads files relative to the property * VelocityEngine.FILE_RESOURCE_LOADER_PATH. So if we can find the template ourselves then we can * infer what the property value should be so that velocity works ok. */ private void inferVelocityLoaderPath(VelocityEngine ve) throws IOException { String defaultPath = (String) ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH); if (null == defaultPath || StringUtils.isEmpty(defaultPath)) { URL url = IOUtils.getResourceAsUrl(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE, getClass()); if (FILE.equals(url.getProtocol())) { String path = FileUtils.getResourcePath(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE, getClass()); if (!StringUtils.isEmpty(path)) { File fullPath = new File(path); File target = new File(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE); // drop trailing files until we are at the relative parent while (null != target && !StringUtils.isEmpty(target.getPath())) { env.log(fullPath.getPath() + " - " + target.getPath()); target = target.getParentFile(); fullPath = fullPath.getParentFile(); } path = fullPath.getPath(); if (path.endsWith("!")) { path = path + File.separator; } getEnv().log(VelocityEngine.FILE_RESOURCE_LOADER_PATH + " = " + path); ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path); } } else if (JAR.equals(url.getProtocol())) { env.log(url.toString()); ve.setProperty(VelocityEngine.RESOURCE_LOADER, "class"); ve.setProperty(MAGIC_VELOCITY_RESOURCE_LOADER, ClasspathResourceLoader.class.getName()); } } }
/** * Takes the log output from the standard CXF LoggingInterceptor, disassembles it, pretty-prints * the XML payload, then puts it all back together again. */ protected static String formatXmlPayload(String originalLogString) { String[] lines = originalLogString.split("\n"); // Figure out which line has the payload on it int payloadLine = -1; for (int i = 0; i < lines.length; ++i) { if (lines[i].startsWith("Payload: ")) { payloadLine = i; break; } } if (payloadLine == -1) { System.err.println("Could not find a line which begins with 'Payload: '"); return originalLogString; } // Extract the XML payload and format it String payload = lines[payloadLine]; String xml = StringUtils.substringAfter(payload, "Payload: "); XmlPrettyPrinter pp = new XmlPrettyPrinter(); try { xml = (String) pp.transform(xml); } catch (MuleException e) { System.err.println(e.getMessage()); } // Replace the payload line with the formatted XML and put it all back together again lines[payloadLine] = "Payload: \n" + xml; return StringUtils.join(lines, "\n"); }
/** @return Returns the outputMessage. */ public String getOutputMessage() { if (StringUtils.isNotBlank(resourceBundle) && StringUtils.isNotBlank(outputMessageCode)) { return StdioMessageFactory.getString(resourceBundle, outputMessageCode); } return outputMessage; }
protected void createStore() throws InitialisationException, RecoverableException { if (StringUtils.equals(storeType, "file")) { store = new FilePersistenceStore(); } else if (StringUtils.equals(storeType, "xmldb")) { store = new XmlDbPersistenceStore(); } if (store != null) { store.initialise(); } }
public String getStatement(ImmutableEndpoint endpoint) { String writeStmt = endpoint.getEndpointURI().getAddress(); String str; if ((str = getQuery(endpoint, writeStmt)) != null) { writeStmt = str; } writeStmt = StringUtils.trimToEmpty(writeStmt); if (StringUtils.isBlank(writeStmt)) { throw new IllegalArgumentException("Missing statement"); } return writeStmt; }
public String getDetailedMessage() { MuleException e = ExceptionHelper.getRootMuleException(this); if (!e.equals(this)) { return getMessage(); } StringBuffer buf = new StringBuffer(1024); buf.append(SystemUtils.LINE_SEPARATOR) .append(StringUtils.repeat('*', 80)) .append(SystemUtils.LINE_SEPARATOR); buf.append("Message : ").append(message).append(SystemUtils.LINE_SEPARATOR); buf.append("Type : ") .append(getClass().getName()) .append(SystemUtils.LINE_SEPARATOR); buf.append("Code : ") .append("MULE_ERROR-") .append(getExceptionCode() + getMessageCode()) .append(SystemUtils.LINE_SEPARATOR); // buf.append("Msg Code : // ").append(getMessageCode()).append(SystemUtils.LINE_SEPARATOR); Map info = ExceptionHelper.getExceptionInfo(this); for (Iterator iterator = info.keySet().iterator(); iterator.hasNext(); ) { String s = (String) iterator.next(); int pad = 22 - s.length(); buf.append(s); if (pad > 0) { buf.append(StringUtils.repeat(' ', pad)); } buf.append(": "); buf.append(info.get(s)).append(SystemUtils.LINE_SEPARATOR); } // print exception stack buf.append(StringUtils.repeat('*', 80)).append(SystemUtils.LINE_SEPARATOR); buf.append(CoreMessages.exceptionStackIs()).append(SystemUtils.LINE_SEPARATOR); buf.append(ExceptionHelper.getExceptionStack(this)); buf.append(StringUtils.repeat('*', 80)).append(SystemUtils.LINE_SEPARATOR); buf.append(CoreMessages.rootStackTrace()).append(SystemUtils.LINE_SEPARATOR); Throwable root = ExceptionHelper.getRootException(this); StringWriter w = new StringWriter(); PrintWriter p = new PrintWriter(w); root.printStackTrace(p); buf.append(w.toString()).append(SystemUtils.LINE_SEPARATOR); buf.append(StringUtils.repeat('*', 80)).append(SystemUtils.LINE_SEPARATOR); return buf.toString(); }
public void initialise() throws InitialisationException { if (wireFormat == null) { wireFormat = new SerializationWireFormat(); } try { if (StringUtils.isEmpty(serverUri)) { // no serverUrl specified, warn a user logger.warn( "No serverUriUrl specified, MuleAdminAgent will not start. E.g. use " + "<mule:admin-agent serverUri=\"tcp://example.com:60504\"/> "); // abort the agent registration process managementContext.getRegistry().unregisterAgent(this.getName()); return; } // Check for override if (ModelHelper.isComponentRegistered(MuleManagerComponent.MANAGER_COMPONENT_NAME)) { logger.info("Mule manager component has already been initialised, ignoring server url"); } else { if (managementContext.getRegistry().lookupConnector(DEFAULT_MANAGER_ENDPOINT) != null) { throw new AlreadyInitialisedException("Server Components", this); } MuleEndpoint writableEndpoint; // Check to see if we have an endpoint identifier UMOImmutableEndpoint endpoint = managementContext.getRegistry().lookupEndpoint(serverUri); if (endpoint == null) { UMOEndpointURI endpointUri = new MuleEndpointURI(serverUri); UMOConnector connector = TransportFactory.getOrCreateConnectorByProtocol(endpointUri); // If this connector has already been initialised i.e. it's a // pre-existing connector don't reinit if (managementContext.getRegistry().lookupConnector(connector.getName()) == null) { connector.setName(DEFAULT_MANAGER_ENDPOINT); connector.initialise(); managementContext.getRegistry().registerConnector(connector); } writableEndpoint = new MuleEndpoint(); writableEndpoint.setConnector(connector); writableEndpoint.setEndpointURI(endpointUri); } else { writableEndpoint = new MuleEndpoint(endpoint); } logger.info("Registering Admin listener on: " + serverUri); UMODescriptor descriptor = MuleManagerComponent.getDescriptor( writableEndpoint, wireFormat, RegistryContext.getConfiguration().getDefaultEncoding(), RegistryContext.getConfiguration().getDefaultSynchronousEventTimeout()); ModelHelper.registerSystemComponent(descriptor); } } catch (UMOException e) { throw new InitialisationException(e, this); } }
public final LifecycleTransitionResult initialise() throws InitialisationException { if (securityManager == null) { securityManager = muleContext.getSecurityManager(); } if (securityManager == null) { throw new InitialisationException(CoreMessages.authSecurityManagerNotSet(), this); } // This filter may only allow authentication on a subset of registered // security providers if (securityProviders != null) { SecurityManager localManager = new MuleSecurityManager(); String[] sp = StringUtils.splitAndTrim(securityProviders, ","); for (int i = 0; i < sp.length; i++) { SecurityProvider provider = securityManager.getProvider(sp[i]); if (provider != null) { localManager.addProvider(provider); } else { throw new InitialisationException( CoreMessages.objectNotRegistered("Security Provider", sp[i]), this); } } securityManager = localManager; } // further functionality moved to lazy initialisation return LifecycleTransitionResult.OK; }
@Override protected ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { SysMsgCommand msgCmd = (SysMsgCommand) command; log.info("SysMsgDetailController:onSubmit called."); NotificationDto sysMessage = msgCmd.getMsg(); String btn = request.getParameter("btn"); if ("delete".equalsIgnoreCase(btn)) { if (sysMessage.getType() == NotificationType.SYSTEM) { return null; } sysMessageService.removeMessage(sysMessage.getMsgId()); ModelAndView mav = new ModelAndView("/deleteconfirm"); mav.addObject("msg", "Location has been successfully deleted."); return mav; } else { if (msgCmd.getTemplateMethod() == 0) { MultipartFile providerScriptFile = msgCmd.getProviderScriptFile(); String providerScriptFileName = ""; if (providerScriptFile != null && providerScriptFile.getSize() > 0) { providerScriptFileName = providerScriptFile.getOriginalFilename(); String filePath = res.getString("scriptRoot") + "/msgprovider/" + providerScriptFileName; File dest = new File(filePath); try { providerScriptFile.transferTo(dest); sysMessage.setProviderScriptName(providerScriptFileName); sysMessage.setMailTemplate(null); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } else { MailTemplateDto mailTemplateDto = mailTemplateWebService .getTemplateById(msgCmd.getSelectedTemplateId()) .getMailTemplate(); sysMessage.setMailTemplate(mailTemplateDto); sysMessage.setProviderScriptName(null); } if (StringUtils.isEmpty(sysMessage.getMsgId())) { sysMessageService.addMessage(sysMessage); } else { sysMessageService.updateMessage(sysMessage); } } ModelAndView mav = new ModelAndView(new RedirectView(redirectView, true)); mav.addObject("sysMsgCmd", msgCmd); return mav; }
@Override public Object makeObject() throws Exception { StreamSource source = XsltTransformer.this.getStreamSource(); String factoryClassName = XsltTransformer.this.getXslTransformerFactory(); TransformerFactory factory; if (PREFERRED_TRANSFORMER_FACTORY.equals(factoryClassName) && !ClassUtils.isClassOnPath(factoryClassName, getClass())) { logger.warn( "Preferred Transfomer Factory " + PREFERRED_TRANSFORMER_FACTORY + " not on classpath and no default is set, defaulting to JDK"); factoryClassName = null; } if (StringUtils.isNotEmpty(factoryClassName)) { factory = (TransformerFactory) ClassUtils.instanciateClass(factoryClassName, ClassUtils.NO_ARGS, this.getClass()); } else { // fall back to JDK default try { factory = TransformerFactory.newInstance(); } catch (TransformerFactoryConfigurationError e) { System.setProperty( "javax.xml.transform.TransformerFactory", XMLUtils.TRANSFORMER_FACTORY_JDK5); factory = TransformerFactory.newInstance(); } } factory.setURIResolver(getUriResolver()); return factory.newTransformer(source); }
public class HttpUtilEchoTestCase extends FunctionalTestCase { private static final String SMALL_PAYLOAD = "This is a test."; private static final String BIG_PAYLOAD = StringUtils.repeat(SMALL_PAYLOAD, 100); private final HttpUtil util = new HttpUtilImpl(); @Rule public DynamicPort port = new DynamicPort("port1"); @Override protected String getConfigFile() { return "http-util-config.xml"; } @Test public void testSmallPayload() throws Exception { postAndAssert(SMALL_PAYLOAD); } @Test public void testBigPayload() throws Exception { postAndAssert(BIG_PAYLOAD); } private void postAndAssert(String payload) { assertEquals( payload, util.post(String.format("http://localhost:%d/echo", port.getNumber()), payload)); } }
public SleepyTask(String name, long sleepTime) { if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("SleepyTask needs a name!"); } this.name = name; this.sleepTime = sleepTime; }
protected void parseChild( Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { Element parent = (Element) element.getParentNode(); String serviceName = parent.getAttribute(ATTRIBUTE_NAME); builder.addPropertyReference("service", serviceName); // Create a BeanDefinition for the nested object factory and set it a // property value for the component AbstractBeanDefinition objectFactoryBeanDefinition = new GenericBeanDefinition(); objectFactoryBeanDefinition.setBeanClass(OBJECT_FACTORY_TYPE); objectFactoryBeanDefinition .getPropertyValues() .addPropertyValue(AbstractObjectFactory.ATTRIBUTE_OBJECT_CLASS, componentInstanceClass); objectFactoryBeanDefinition.setInitMethodName(Initialisable.PHASE_NAME); objectFactoryBeanDefinition.setDestroyMethodName(Disposable.PHASE_NAME); Map props = new HashMap(); for (int i = 0; i < element.getAttributes().getLength(); i++) { Node n = element.getAttributes().item(i); props.put(n.getLocalName(), n.getNodeValue()); } String returnData = null; NodeList list = element.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { if ("return-data".equals(list.item(i).getLocalName())) { Element rData = (Element) list.item(i); if (StringUtils.isNotEmpty(rData.getAttribute("file"))) { String file = rData.getAttribute("file"); try { returnData = IOUtils.getResourceAsString(file, getClass()); } catch (IOException e) { throw new BeanCreationException("Failed to load test-data resource: " + file, e); } } else { returnData = rData.getTextContent(); } } else if ("callback".equals(list.item(i).getLocalName())) { Element ele = (Element) list.item(i); String c = ele.getAttribute("class"); try { EventCallback cb = (EventCallback) ClassUtils.instanciateClass(c); props.put("eventCallback", cb); } catch (Exception e) { throw new BeanCreationException("Failed to load event-callback: " + c, e); } } } if (returnData != null) { props.put("returnData", returnData); } objectFactoryBeanDefinition.getPropertyValues().addPropertyValue("properties", props); builder.addPropertyValue("objectFactory", objectFactoryBeanDefinition); super.parseChild(element, parserContext, builder); }
// @Override public BeanDefinitionBuilder createBeanDefinitionBuilder(Element element, Class beanClass) { BeanDefinitionBuilder builder = super.createBeanDefinitionBuilder(element, beanClass); String global = element.getAttribute(AbstractMuleBeanDefinitionParser.ATTRIBUTE_REF); if (StringUtils.isNotBlank(global)) { builder.addConstructorArgReference(global); builder.addDependsOn(global); } return builder; }
protected BodyPart getBodyPartForAttachment(DataHandler handler, String name) throws MessagingException { BodyPart part = new MimeBodyPart(); part.setDataHandler(handler); part.setDescription(name); part.setFileName(StringUtils.defaultString(handler.getName(), name)); return part; }
/** {@inheritDoc} */ public String getDomainName() { // TODO add some config options to the JmxAgent String domain = DEFAULT_JMX_DOMAIN_PREFIX; String instanceId = StringUtils.defaultIfEmpty(MuleManager.getInstance().getId(), StringUtils.EMPTY); if (instanceId.length() > 0) { domain += "." + instanceId; } JmxRegistrationContext ctx = JmxRegistrationContext.getCurrent(); String resolvedDomain = ctx.getResolvedDomain(); if (StringUtils.isBlank(resolvedDomain)) { domain = resolveDomainClash(domain); ctx.setResolvedDomain(domain); } return domain; }
public static Map cleanAndAdd(UMOEventContext muleEventContext) { Map props = new HashMap(); UMOMessage currentMessage = muleEventContext.getMessage(); final String SOAP_METHODS = "soapMethods"; for (Iterator iterator = currentMessage.getPropertyNames().iterator(); iterator.hasNext(); ) { String name = (String) iterator.next(); if (!StringUtils.equals(name, SOAP_METHODS) && !StringUtils.equals(name, SoapConstants.SOAP_ACTION_PROPERTY) && !StringUtils.equals(name, MuleProperties.MULE_METHOD_PROPERTY) && (!name.startsWith(MuleProperties.PROPERTY_PREFIX) || StringUtils.equals(name, MuleProperties.MULE_USER_PROPERTY)) && !HttpConstants.ALL_HEADER_NAMES.containsValue(name) && !StringUtils.equals(name, HttpConnector.HTTP_STATUS_PROPERTY)) { props.put(name, currentMessage.getProperty(name)); } } return props; }
@Test public void getParameterSummaryParameterWithEmptyComment() throws Exception { when(elements.getDocComment(executableElement)) .thenReturn( "\n" + " Bla bla bla\n" + " \n" + " @param name the name\n" + " @param content"); JavaDocUtils javaDocUtils = new JavaDocUtils(elements); assertTrue(StringUtils.isBlank(javaDocUtils.getParameterSummary("content", executableElement))); }
/** Copies a given app archive with a given target name to the apps folder for deployment */ private void addAppArchive(URL url, String targetFile) throws IOException { // copy is not atomic, copy to a temp file and rename instead (rename is atomic) final String tempFileName = new File((targetFile == null ? url.getFile() : targetFile) + ".part").getName(); final File tempFile = new File(appsDir, tempFileName); FileUtils.copyURLToFile(url, tempFile); boolean renamed = tempFile.renameTo(new File(StringUtils.removeEnd(tempFile.getAbsolutePath(), ".part"))); if (!renamed) { throw new IllegalStateException("Unable to add application archive"); } }
public Router parseRouter(Annotation annotation) throws MuleException { AbstractResponseCallbackAggregator router; Reply reply = (Reply) annotation; router = new SingleResponseWithCallbackRouter(); if (StringUtils.isNotBlank(reply.callback())) { router.setCallbackMethod(reply.callback()); } router.setTimeout(reply.replyTimeout()); router.setFailOnTimeout(reply.failOnTimeout()); return router; }
public void setScope(String scope) { if (StringUtils.isBlank(scope)) { // ignore and use defaults return; } PropertyScope ps = PropertyScope.get(scope.toLowerCase().trim()); if (ps == null) { throw new IllegalArgumentException( String.format("'%s' is not a valid property scope.", scope)); } this.scope = ps; }
@Test public void testConcurrentHashMapConverter() throws ClassNotFoundException, IllegalAccessException, InstantiationException { ConcurrentHashMap<Object, Object> map = new ConcurrentHashMap<Object, Object>(); map.put("foo", "bar"); XStream xstream = new XStreamFactory().getInstance(); String mapXML = xstream.toXML(map); assertNotNull(mapXML); assertTrue(StringUtils.isNotEmpty(mapXML)); Object newMap = xstream.fromXML(mapXML); assertNotNull(newMap); assertTrue(newMap instanceof ConcurrentHashMap); assertEquals(1, ((Map<?, ?>) newMap).size()); assertEquals("bar", ((Map<?, ?>) newMap).get("foo")); }
public static void main(String[] args) { LoanConsumer loanConsumer = null; try { String config = SystemUtils.getCommandLineOption("-config", args); if (StringUtils.isNotBlank(config)) { loanConsumer = new LoanConsumer(config); int i = 100; String requests = SystemUtils.getCommandLineOption("-req", args); if (requests != null) { i = Integer.parseInt(requests); } String sync = SystemUtils.getCommandLineOption("-sync", args); if (sync != null) { synchronous = Boolean.valueOf(sync).booleanValue(); } if (synchronous) { long start = System.currentTimeMillis(); List results = loanConsumer.requestSend(i, "vm://LoanBrokerRequests"); System.out.println("Number or quotes received: " + results.size()); List output = new ArrayList(results.size()); int x = 1; for (Iterator iterator = results.iterator(); iterator.hasNext(); x++) { LoanQuote quote = (LoanQuote) iterator.next(); output.add(x + ". " + quote.toString()); } System.out.println(StringMessageUtils.getBoilerPlate(output, '*', 80)); long cur = System.currentTimeMillis(); System.out.println(DateUtils.getFormattedDuration(cur - start)); System.out.println("Avg request: " + ((cur - start) / x)); } else { loanConsumer.requestDispatch(i, "vm://LoanBrokerRequests"); } } else { loanConsumer = new LoanConsumer(getInteractiveConfig()); loanConsumer.run(synchronous); } } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(System.err); System.exit(1); } }
/** * Generate a URL based on the process name and ID such as "bpm://myProcess/2342" If the * parameters are missing, and <code>allowGlobalReceiver</code> is true, the GLOBAL_RECEIVER is * returned. */ public String toUrl(String processName, Object processId) { String url = getProtocol() + "://"; if (StringUtils.isNotEmpty(processName)) { url += processName; if (processId != null) { url += "/" + processId; } } else if (isAllowGlobalReceiver()) { return GLOBAL_RECEIVER; } else { throw new IllegalArgumentException( "No valid URL could be created for the given process name and ID: processName = " + processName + ", processId = " + processId); } return url; }
@Override protected void doConnect() throws Exception { SessionDetails session = castConnector().getSessionDetails(endpoint); Store store = session.newStore(); store.connect(); folder = store.getFolder(castConnector().getMailboxFolder()); if (castConnector().getMoveToFolder() != null) { moveToFolder = store.getFolder(castConnector().getMoveToFolder()); moveToFolder.open(Folder.READ_WRITE); } // set default value if empty/null if (StringUtils.isEmpty(backupFolder)) { this.backupFolder = connector.getMuleContext().getConfiguration().getWorkingDirectory() + "/mail/" + folder.getName(); } if (backupFolder != null && !this.backupFolder.endsWith(File.separator)) { this.backupFolder += File.separator; } }
@Override public void processReplyTo(MuleEvent event, MuleMessage returnMessage, Object replyTo) throws MuleException { Destination replyToDestination = null; MessageProducer replyToProducer = null; Session session = null; try { // now we need to send the response if (replyTo instanceof Destination) { replyToDestination = (Destination) replyTo; } if (replyToDestination == null) { super.processReplyTo(event, returnMessage, replyTo); return; } // This is a work around for JmsTransformers where the current endpoint needs // to be set on the transformer so that a JMSMessage can be created correctly (the transformer // needs a Session) Class srcType = returnMessage.getPayload().getClass(); for (Iterator iterator = getTransformers().iterator(); iterator.hasNext(); ) { Transformer t = (Transformer) iterator.next(); if (t.isSourceDataTypeSupported(DataTypeFactory.create(srcType))) { if (t.getEndpoint() == null) { t.setEndpoint(getEndpoint(event, "jms://temporary")); break; } } } returnMessage.applyTransformers(getTransformers()); Object payload = returnMessage.getPayload(); if (replyToDestination instanceof Topic && replyToDestination instanceof Queue && connector.getJmsSupport() instanceof Jms102bSupport) { logger.error( StringMessageUtils.getBoilerPlate( "ReplyTo destination implements both Queue and Topic " + "while complying with JMS 1.0.2b specification. " + "Please report your application server or JMS vendor name and version " + "to dev<_at_>mule.codehaus.org or http://mule.mulesource.org/jira")); } final boolean topic = connector.getTopicResolver().isTopic(replyToDestination); session = connector.getSession(false, topic); Message replyToMessage = JmsMessageUtils.toMessage(payload, session); processMessage(replyToMessage, event); if (logger.isDebugEnabled()) { logger.debug( "Sending jms reply to: " + replyToDestination + "(" + replyToDestination.getClass().getName() + ")"); } replyToProducer = connector.getJmsSupport().createProducer(session, replyToDestination, topic); // QoS support MuleMessage eventMsg = event.getMessage(); String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY); String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY); String persistentDeliveryString = (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY); String correlationIDString = replyToMessage.getJMSCorrelationID(); if (StringUtils.isBlank(correlationIDString)) { correlationIDString = (String) eventMsg.getProperty(JmsConstants.JMS_MESSAGE_ID); replyToMessage.setJMSCorrelationID(correlationIDString); } event.getService().getStatistics().incSentReplyToEvent(); final ImmutableEndpoint endpoint = event.getEndpoint(); if (ttlString == null && priorityString == null && persistentDeliveryString == null) { connector.getJmsSupport().send(replyToProducer, replyToMessage, topic, endpoint); } else { long ttl = Message.DEFAULT_TIME_TO_LIVE; int priority = Message.DEFAULT_PRIORITY; if (ttlString != null) { ttl = Long.parseLong(ttlString); } if (priorityString != null) { priority = Integer.parseInt(priorityString); } boolean persistent = StringUtils.isNotBlank(persistentDeliveryString) ? Boolean.valueOf(persistentDeliveryString) : connector.isPersistentDelivery(); connector .getJmsSupport() .send(replyToProducer, replyToMessage, persistent, priority, ttl, topic, endpoint); } logger.info( "Reply Message sent to: " + replyToDestination + " with correlationID:" + correlationIDString); } catch (Exception e) { throw new DispatchException( JmsMessages.failedToCreateAndDispatchResponse(replyToDestination), returnMessage, null, e); } finally { connector.closeQuietly(replyToProducer); final Transaction transaction = TransactionCoordination.getInstance().getTransaction(); if (transaction == null) { if (logger.isDebugEnabled()) { logger.debug("Closing non-TX replyTo session: " + session); } connector.closeQuietly(session); } else if (logger.isDebugEnabled()) { logger.debug("Not closing TX replyTo session: " + session); } } }
private MuleMessage dispatchMessage(MuleEvent event) throws Exception { Session session = null; MessageProducer producer = null; MessageConsumer consumer = null; Destination replyTo = null; boolean transacted = false; boolean cached = false; boolean useReplyToDestination; final Transaction muleTx = TransactionCoordination.getInstance().getTransaction(); if (logger.isDebugEnabled()) { logger.debug( "dispatching on endpoint: " + event.getEndpoint().getEndpointURI() + ". MuleEvent id is: " + event.getId() + ". Outbound transformers are: " + event.getEndpoint().getTransformers()); } // assume session is transacted first, and thus, managed boolean sessionManaged = true; try { session = connector.getSessionFromTransaction(); if (session != null) { transacted = true; } // Should we be caching sessions? Note this is not part of the JMS spec. // and is turned off by default. else if (event .getMessage() .getBooleanProperty( JmsConstants.CACHE_JMS_SESSIONS_PROPERTY, connector.isCacheJmsSessions())) { sessionManaged = false; cached = true; if (cachedSession != null) { session = cachedSession; } else { session = connector.getSession(event.getEndpoint()); cachedSession = session; } } else { // by now we're running with a different connector and connection sessionManaged = muleTx != null && muleTx.isXA(); session = connector.getSession(event.getEndpoint()); if (event.getEndpoint().getTransactionConfig().isTransacted()) { transacted = true; } } // If a transaction is running, we can not receive any messages // in the same transaction using a replyTo destination useReplyToDestination = returnResponse(event) && !transacted; boolean topic = connector.getTopicResolver().isTopic(event.getEndpoint(), true); Destination dest = connector.getJmsSupport().createDestination(session, endpoint); producer = connector.getJmsSupport().createProducer(session, dest, topic); preTransformMessage(event.getMessage()); Object message = event.transformMessage(); if (!(message instanceof Message)) { throw new DispatchException( JmsMessages.checkTransformer("JMS message", message.getClass(), connector.getName()), event.getMessage(), event.getEndpoint()); } Message msg = (Message) message; MuleMessage eventMsg = event.getMessage(); replyTo = getReplyToDestination(msg, session, event, useReplyToDestination, topic); // Set the replyTo property if (replyTo != null) { msg.setJMSReplyTo(replyTo); } // Allow overrides to alter the message if necessary processMessage(msg, event); // QoS support String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY); String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY); String persistentDeliveryString = (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY); long ttl = StringUtils.isNotBlank(ttlString) ? NumberUtils.toLong(ttlString) : Message.DEFAULT_TIME_TO_LIVE; int priority = StringUtils.isNotBlank(priorityString) ? NumberUtils.toInt(priorityString) : Message.DEFAULT_PRIORITY; boolean persistent = StringUtils.isNotBlank(persistentDeliveryString) ? BooleanUtils.toBoolean(persistentDeliveryString) : connector.isPersistentDelivery(); // If we are honouring the current QoS message headers we need to use the ones set on the // current message if (connector.isHonorQosHeaders()) { Object priorityProp = eventMsg.getProperty(JmsConstants.JMS_PRIORITY); Object deliveryModeProp = eventMsg.getProperty(JmsConstants.JMS_DELIVERY_MODE); if (priorityProp != null) { priority = NumberUtils.toInt(priorityProp); } if (deliveryModeProp != null) { persistent = NumberUtils.toInt(deliveryModeProp) == DeliveryMode.PERSISTENT; } } if (logger.isDebugEnabled()) { logger.debug("Sending message of type " + ClassUtils.getSimpleName(msg.getClass())); logger.debug( "Sending JMS Message type " + msg.getJMSType() + "\n JMSMessageID=" + msg.getJMSMessageID() + "\n JMSCorrelationID=" + msg.getJMSCorrelationID() + "\n JMSDeliveryMode=" + (persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT) + "\n JMSPriority=" + priority + "\n JMSReplyTo=" + msg.getJMSReplyTo()); } connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic, endpoint); if (useReplyToDestination && replyTo != null) { consumer = createReplyToConsumer(msg, event, session, replyTo, topic); if (topic) { // need to register a listener for a topic Latch l = new Latch(); ReplyToListener listener = new ReplyToListener(l); consumer.setMessageListener(listener); connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic, endpoint); int timeout = event.getTimeout(); if (logger.isDebugEnabled()) { logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo); } l.await(timeout, TimeUnit.MILLISECONDS); consumer.setMessageListener(null); listener.release(); Message result = listener.getMessage(); if (result == null) { logger.debug("No message was returned via replyTo destination"); return new DefaultMuleMessage(NullPayload.getInstance(), connector.getMuleContext()); } else { MessageAdapter adapter = connector.getMessageAdapter(result); return new DefaultMuleMessage( JmsMessageUtils.toObject( result, connector.getSpecification(), endpoint.getEncoding()), adapter, connector.getMuleContext()); } } else { int timeout = event.getTimeout(); if (logger.isDebugEnabled()) { logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo); } Message result = consumer.receive(timeout); if (result == null) { logger.debug("No message was returned via replyTo destination " + replyTo); return new DefaultMuleMessage(NullPayload.getInstance(), connector.getMuleContext()); } else { MessageAdapter adapter = connector.getMessageAdapter(result); return new DefaultMuleMessage( JmsMessageUtils.toObject( result, connector.getSpecification(), endpoint.getEncoding()), adapter, connector.getMuleContext()); } } } return new DefaultMuleMessage( returnOriginalMessageAsReply ? msg : NullPayload.getInstance(), connector.getMuleContext()); } finally { connector.closeQuietly(producer); connector.closeQuietly(consumer); // TODO AP check if TopicResolver is to be utilized for temp destinations as well if (replyTo != null && (replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic)) { if (replyTo instanceof TemporaryQueue) { connector.closeQuietly((TemporaryQueue) replyTo); } else { // hope there are no more non-standard tricks from JMS vendors // here ;) connector.closeQuietly((TemporaryTopic) replyTo); } } if (!sessionManaged && transacted && muleTx instanceof TransactionCollection) { handleMultiTx(session); } // If the session is from the current transaction, it is up to the // transaction to close it. if (session != null && !cached && !transacted) { connector.closeQuietly(session); } } }
public void deploy(String resource) throws IOException { int lastSeparator = resource.lastIndexOf(File.separator); String appName = StringUtils.removeEndIgnoreCase(resource.substring(lastSeparator + 1), ".zip"); deploy(resource, appName); }
private MuleMessage dispatchMessage(MuleEvent event) throws Exception { Session session = null; MessageProducer producer = null; MessageConsumer consumer = null; Destination replyTo = null; boolean transacted = false; boolean cached = false; boolean remoteSync = useRemoteSync(event); if (logger.isDebugEnabled()) { logger.debug( "dispatching on endpoint: " + event.getEndpoint().getEndpointURI() + ". MuleEvent id is: " + event.getId() + ". Outbound transformers are: " + event.getEndpoint().getTransformers()); } try { session = connector.getSessionFromTransaction(); if (session != null) { transacted = true; // If a transaction is running, we can not receive any messages // in the same transaction. if (remoteSync) { throw new IllegalTransactionStateException( JmsMessages.connectorDoesNotSupportSyncReceiveWhenTransacted()); } } // Should we be caching sessions? Note this is not part of the JMS spec. // and is turned off by default. else if (event .getMessage() .getBooleanProperty( JmsConstants.CACHE_JMS_SESSIONS_PROPERTY, connector.isCacheJmsSessions())) { cached = true; if (cachedSession != null) { session = cachedSession; } else { session = connector.getSession(event.getEndpoint()); cachedSession = session; } } else { session = connector.getSession(event.getEndpoint()); if (event.getEndpoint().getTransactionConfig().isTransacted()) { transacted = true; } } boolean topic = connector.getTopicResolver().isTopic(event.getEndpoint(), true); Destination dest = connector.createDestinationMule3858Backport(session, endpoint); producer = connector.getJmsSupport().createProducer(session, dest, topic); Object message = event.transformMessage(); if (!(message instanceof Message)) { throw new DispatchException( JmsMessages.checkTransformer("JMS message", message.getClass(), connector.getName()), event.getMessage(), event.getEndpoint()); } Message msg = (Message) message; if (event.getMessage().getCorrelationId() != null) { msg.setJMSCorrelationID(event.getMessage().getCorrelationId()); } MuleMessage eventMsg = event.getMessage(); // Some JMS implementations might not support the ReplyTo property. if (connector.supportsProperty(JmsConstants.JMS_REPLY_TO)) { Object tempReplyTo = eventMsg.removeProperty(JmsConstants.JMS_REPLY_TO); if (tempReplyTo == null) { // It may be a Mule URI or global endpoint Ref tempReplyTo = eventMsg.removeProperty(MuleProperties.MULE_REPLY_TO_PROPERTY); if (tempReplyTo != null) { if (tempReplyTo.toString().startsWith("jms://")) { tempReplyTo = tempReplyTo.toString().substring(6); } else { EndpointBuilder epb = event .getMuleContext() .getRegistry() .lookupEndpointBuilder(tempReplyTo.toString()); if (epb != null) { tempReplyTo = epb.buildOutboundEndpoint().getEndpointURI().getAddress(); } } } } if (tempReplyTo != null) { if (tempReplyTo instanceof Destination) { replyTo = (Destination) tempReplyTo; } else { // TODO AP should this drill-down be moved into the resolver as well? boolean replyToTopic = false; String reply = tempReplyTo.toString(); int i = reply.indexOf(":"); if (i > -1) { // TODO MULE-1409 this check will not work for ActiveMQ 4.x, // as they have temp-queue://<destination> and temp-topic://<destination> URIs // Extract to a custom resolver for ActiveMQ4.x // The code path can be exercised, e.g. by a LoanBrokerESBTestCase String qtype = reply.substring(0, i); replyToTopic = JmsConstants.TOPIC_PROPERTY.equalsIgnoreCase(qtype); reply = reply.substring(i + 1); } replyTo = connector.getJmsSupport().createDestination(session, reply, replyToTopic); } } // Are we going to wait for a return event ? if (remoteSync && replyTo == null) { replyTo = connector.getJmsSupport().createTemporaryDestination(session, topic); } // Set the replyTo property if (replyTo != null) { msg.setJMSReplyTo(replyTo); } // Are we going to wait for a return event ? if (remoteSync) { try { consumer = connector.getJmsSupport().createConsumer(session, replyTo, topic); } catch (Exception e) { logger.warn(e); } } } // QoS support String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY); String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY); String persistentDeliveryString = (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY); long ttl = StringUtils.isNotBlank(ttlString) ? NumberUtils.toLong(ttlString) : Message.DEFAULT_TIME_TO_LIVE; int priority = StringUtils.isNotBlank(priorityString) ? NumberUtils.toInt(priorityString) : Message.DEFAULT_PRIORITY; boolean persistent = StringUtils.isNotBlank(persistentDeliveryString) ? BooleanUtils.toBoolean(persistentDeliveryString) : connector.isPersistentDelivery(); if (connector.isHonorQosHeaders()) { int priorityProp = eventMsg.getIntProperty(JmsConstants.JMS_PRIORITY, Connector.INT_VALUE_NOT_SET); int deliveryModeProp = eventMsg.getIntProperty(JmsConstants.JMS_DELIVERY_MODE, Connector.INT_VALUE_NOT_SET); if (priorityProp != Connector.INT_VALUE_NOT_SET) { priority = priorityProp; } if (deliveryModeProp != Connector.INT_VALUE_NOT_SET) { persistent = deliveryModeProp == DeliveryMode.PERSISTENT; } } if (logger.isDebugEnabled()) { logger.debug("Sending message of type " + ClassUtils.getSimpleName(msg.getClass())); } if (consumer != null && topic) { // need to register a listener for a topic Latch l = new Latch(); ReplyToListener listener = new ReplyToListener(l); consumer.setMessageListener(listener); connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic); int timeout = event.getTimeout(); if (logger.isDebugEnabled()) { logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo); } l.await(timeout, TimeUnit.MILLISECONDS); consumer.setMessageListener(null); listener.release(); Message result = listener.getMessage(); if (result == null) { logger.debug("No message was returned via replyTo destination"); return null; } else { MessageAdapter adapter = connector.getMessageAdapter(result); return new DefaultMuleMessage( JmsMessageUtils.toObject( result, connector.getSpecification(), endpoint.getEncoding()), adapter); } } else { connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic); if (consumer != null) { int timeout = event.getTimeout(); if (logger.isDebugEnabled()) { logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo); } Message result = consumer.receive(timeout); if (result == null) { logger.debug("No message was returned via replyTo destination"); return null; } else { MessageAdapter adapter = connector.getMessageAdapter(result); return new DefaultMuleMessage( JmsMessageUtils.toObject( result, connector.getSpecification(), endpoint.getEncoding()), adapter); } } } return null; } finally { connector.closeQuietly(producer); connector.closeQuietly(consumer); // TODO AP check if TopicResolver is to be utilized for temp destinations as well if (replyTo != null && (replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic)) { if (replyTo instanceof TemporaryQueue) { connector.closeQuietly((TemporaryQueue) replyTo); } else { // hope there are no more non-standard tricks from JMS vendors // here ;) connector.closeQuietly((TemporaryTopic) replyTo); } } // If the session is from the current transaction, it is up to the // transaction to close it. if (session != null && !cached && !transacted) { connector.closeQuietly(session); } } }