@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); }
static { try { consumableClasses.add( ClassUtils.loadClass("javax.xml.stream.XMLStreamReader", DefaultMuleMessage.class)); } catch (ClassNotFoundException e) { } }
public void initialise() throws InitialisationException { if (configFile == null) { if (configuration != null) { try { configure(configuration); return; } catch (ContainerException e) { throw new InitialisationException(e, this); } } else { return; } } try { if (ClassUtils.getResource(configFile, getClass()) == null) { logger.warn( "Spring config resource: " + configFile + " not found on class path, attempting to load it from local file"); setExternalBeanFactory(new FileSystemXmlApplicationContext(configFile)); } else { logger.info("Loading Spring config from classpath, resource is: " + configFile); setExternalBeanFactory(new ClassPathXmlApplicationContext(configFile)); } } catch (BeansException e) { throw new InitialisationException( new ConfigurationException( CoreMessages.failedToLoad("Application Context: " + configFile), e), this); } }
protected void doInitialise() throws InitialisationException { try { if (bpms == null) { if (bpmsClass != null) { logger.info("Instantiating BPMS from the default constructor for " + bpmsClass); bpms = (BPMS) ClassUtils.instanciateClass(bpmsClass, new Object[0]); } else { throw new ConfigurationException( MessageFactory.createStaticMessage( "Either the bpms or bpmsClass property must be set for this connector.")); } } // Set a callback so that the BPMS may generate messages within Mule. bpms.setMessageService(this); // The MuleClient is used as a global dispatcher. // TODO MULE-1221 It would be cleaner to use something like the dynamic:// transport if ((allowGlobalDispatcher == true) && (muleClient == null)) { muleClient = new MuleClient(false); } } catch (Exception e) { throw new InitialisationException(e, this); } }
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 String toString() { final StringBuffer sb = new StringBuffer(80); sb.append(ClassUtils.getSimpleName(this.getClass())); sb.append("{this=").append(Integer.toHexString(System.identityHashCode(this))); sb.append(", endpoint=").append(endpoint.getEndpointURI().getUri()); sb.append(", disposed=").append(disposed); sb.append('}'); return sb.toString(); }
protected Class loadClass(String name) { String c = name.replace("/", "."); try { return ClassUtils.loadClass(c, classLoader); } catch (ClassNotFoundException e) { if (logger.isWarnEnabled()) { logger.warn(String.format("%s : %s", c, e.toString())); } return null; } }
public void initialise() throws InitialisationException { if (objectClass == null && objectClassName == null) { throw new InitialisationException( MessageFactory.createStaticMessage("Object factory has not been initialized."), this); } if (objectClass == null && objectClassName != null) { try { objectClass = ClassUtils.getClass(objectClassName); } catch (ClassNotFoundException e) { throw new InitialisationException(e, this); } } }
protected ObjectFilter createFilter(String pattern) { try { if (getSubscriptionFilter() == null) { setSubscriptionFilter(WildcardFilter.class); } ObjectFilter filter = (ObjectFilter) ClassUtils.instanciateClass(getSubscriptionFilter(), new Object[] {pattern}); return filter; } catch (Exception e) { exceptionListener.exceptionThrown(e); return new WildcardFilter(pattern); } }
/** Creates an initialized object instance based on the class and sets any properties. */ public Object getInstance() throws Exception { if (objectClass == null) { throw new InitialisationException( MessageFactory.createStaticMessage("Object factory has not been initialized."), this); } Object object = ClassUtils.instanciateClass(objectClass, ClassUtils.NO_ARGS); if (properties != null) { BeanUtils.populate(object, properties); } fireInitialisationCallbacks(object); return object; }
/* * (non-Javadoc) * * @see org.mule.providers.AbstractConnector#create() */ public void doInitialise() throws InitialisationException { super.doInitialise(); if (queueEvents) { if (queueProfile == null) { queueProfile = MuleManager.getConfiguration().getQueueProfile(); } } try { adapterClass = ClassUtils.loadClass(serviceDescriptor.getMessageAdapter(), getClass()); } catch (ClassNotFoundException e) { throw new InitialisationException( new Message( Messages.FAILED_LOAD_X, "Message Adapter: " + serviceDescriptor.getMessageAdapter()), e); } }
public static Class getErrorClass(int code) { String key = String.valueOf(code); Object clazz = reverseErrorCodes.get(key); if (clazz == null) { return null; } else if (clazz instanceof Class) { return (Class) clazz; } else { try { clazz = ClassUtils.loadClass(clazz.toString(), ExceptionHelper.class); } catch (ClassNotFoundException e) { logger.error(e.getMessage(), e); return null; } reverseErrorCodes.put(key, clazz); return (Class) clazz; } }
public ConnectorServiceDescriptor findService(String service, ConnectorServiceDescriptor csd) throws ConnectorFactoryException { Map finders = new TreeMap(); PropertiesUtils.getPropertiesWithPrefix(csd.getProperties(), "finder.class", finders); StringBuffer buf = new StringBuffer(); for (Iterator iterator = finders.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); try { ClassUtils.loadClass(entry.getValue().toString(), getClass()); String protocol = getProtocolFromKey(entry.getKey().toString()); return ConnectorFactory.getServiceDescriptor(protocol); } catch (ClassNotFoundException e1) { buf.append(entry.getValue().toString()) .append("(") .append(entry.getKey().toString()) .append(")") .append(", "); } } throw new ConnectorServiceException( new Message(Messages.COULD_NOT_FIND_SOAP_PROVIDER_X, buf.toString())); }
public final Object lookupObject(Object key, Class returntype, int scope) { Object o = null; try { o = doLookupObject(key, returntype); if (returntype.isAssignableFrom(o.getClass())) { return o; } else { throw new IllegalArgumentException( "Object was found in registry with key: " + key + ". But object was of type: " + o.getClass().getName() + ", not of expected type: " + returntype); } } catch (ObjectNotFoundException e) { if (logger.isDebugEnabled()) { logger.debug("Failed to find object in Registry ID: " + getRegistryId()); } if (getParent() != null && scope > SCOPE_IMMEDIATE) { if (getParent().isRemote() && scope == SCOPE_REMOTE) { o = getParent().lookupObject(key, returntype); } else if (!getParent().isRemote() && scope >= SCOPE_LOCAL) { o = getParent().lookupObject(key, returntype); } } // Legacy behaviour. Try instantiating the class if (o == null && key.toString().indexOf(".") > 0) { try { o = ClassUtils.instanciateClass(key.toString(), ClassUtils.NO_ARGS, getClass()); } catch (Exception e1) { // logger.error("Failed to reference: " + key, e1); } } return o; } }
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 static Message checkTransformer(String string, Class class1, String name) { return factory.createMessage( BUNDLE_PATH, 13, string, ClassUtils.getSimpleName(class1.getClass()), name); }
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); } } }
@Override public String toString() { return String.format("%s{%s}", ClassUtils.getSimpleName(this.getClass()), getName()); }