diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/MimeEmailMessageHandler.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/MimeEmailMessageHandler.java new file mode 100644 index 000000000..2c88b31bb --- /dev/null +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/MimeEmailMessageHandler.java @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.wso2.carbon.registry.eventing; + +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.description.Parameter; +import org.apache.axis2.transport.mail.MailConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.event.core.Message; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.session.UserRegistry; +import org.wso2.carbon.registry.eventing.events.DispatchEvent; +import org.wso2.carbon.registry.eventing.internal.EventingDataHolder; +import org.wso2.carbon.registry.eventing.template.NotificationTemplate; + +import javax.mail.*; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; +import java.util.Date; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +public class MimeEmailMessageHandler { + + public static final int MIN_THREAD = 8; + public static final int MAX_THREAD = 100; + public static final String MIN_THREAD_NAME = "minThread"; + public static final String MAX_THREAD_NAME = "maxThread"; + public static final String DEFAULT_KEEP_ALIVE_TIME_NAME = "defaultKeepAliveTime"; + public static final long DEFAULT_KEEP_ALIVE_TIME = 20; + private static final Log log = LogFactory.getLog(MimeEmailMessageHandler.class); + private static Session session; + private static ThreadPoolExecutor threadPoolExecutor; + private InternetAddress smtpFromAddress = null; + + /** + * + * @param configContext ConfigurationContext + * @param message Mail body + * @param subject Mail Subject + * @param toAddress email to address + * @throws RegistryException Registry exception + */ + public void sendMimeMessage(ConfigurationContext configContext, String message, String subject, String toAddress) throws RegistryException { + Properties props = new Properties(); + if (configContext != null && configContext.getAxisConfiguration().getTransportOut("mailto") != null) { + List params = configContext.getAxisConfiguration().getTransportOut("mailto").getParameters(); + for (Parameter parm: params) { + props.put(parm.getName(), parm.getValue()); + } + } + if (threadPoolExecutor == null) { + threadPoolExecutor = new ThreadPoolExecutor(MIN_THREAD, MAX_THREAD, DEFAULT_KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue(1000)); + } + String smtpFrom = props.getProperty(MailConstants.MAIL_SMTP_FROM); + + try { + smtpFromAddress = new InternetAddress(smtpFrom); + } catch (AddressException e) { + log.error("Error in retrieving smtp address"); + throw new RegistryException("Error in transforming smtp address"); + } + final String smtpUsername = props.getProperty(MailConstants.MAIL_SMTP_USERNAME); + final String smtpPassword = props.getProperty(MailConstants.MAIL_SMTP_PASSWORD); + if (smtpUsername != null && smtpPassword != null) { + MimeEmailMessageHandler.session = Session.getInstance(props, new Authenticator() { + public PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(smtpUsername, smtpPassword); + } + }); + } else { + MimeEmailMessageHandler.session = Session.getInstance(props); + } + threadPoolExecutor.submit(new EmailSender(toAddress, subject, message.toString(), "text/html")); + } + + /** + * + * @param message Message Object + * @param path Registry path + * @param event Event name + * @return Mail Subject + */ + public String getEmailSubject(Message message, String path,String event){ + String mailHeader = message.getProperty(MailConstants.MAIL_HEADER_SUBJECT); + if (mailHeader == null && (path == null || path.length() == 0)) { + mailHeader = "[" + event + "]"; + } else if (mailHeader == null) { + mailHeader ="[" + event + "] at path: " + path; + } + return mailHeader; + } + + public String getEmailMessage(Message message){ + String emailMessage = null; + DispatchEvent event = (DispatchEvent) message; + String eventType = event.getEvent().getClass().getSimpleName(); + String resourcePath = event.getEvent().getOperationDetails().getPath(); + if (EventingDataHolder.getInstance().getRegistryService() != null) { + try { + UserRegistry registry = EventingDataHolder.getInstance().getRegistryService().getConfigSystemRegistry(); + String mesageContent = event.getEvent().getMessage().toString(); + String className = EventingDataHolder.getInstance().getNotificationConfig().getConfigurationClass(); + Class clazz = Class.forName(className); + Object instance = clazz.newInstance(); + if (instance instanceof NotificationTemplate){ + NotificationTemplate template = (NotificationTemplate) instance; + emailMessage = template.populateEmailMessage(registry,resourcePath,mesageContent,eventType); + } + } catch (InstantiationException e) { + log.warn("Error while instantiating template"); + } catch (IllegalAccessException e) { + log.warn("Error while instantiating template"); + } catch (ClassNotFoundException e) { + log.warn("Error while instantiating template"); + } catch (RegistryException e) { + log.warn("Error while instantiating template"); + } + + } + return emailMessage; + } + + class EmailSender implements Runnable { + String to; + String subject; + String body; + String type; + + EmailSender(String to, String subject, String body, String type) { + this.to = to; + this.subject = subject; + this.body = body; + this.type = type; + } + + /** + * Sending emails to the corresponding Email IDs'. + */ + + @Override + public void run() { + + if (log.isDebugEnabled()) { + log.debug("Format of the email:" + " " + to + "->" + type); + } + //Creating MIME object using initiated session. + + MimeMessage message = new MimeMessage(session); + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(body); + String finalString = stringBuilder.toString(); + //Setting up the Email attributes and Email payload. + + try { + message.setFrom(smtpFromAddress); + message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); + message.setSubject(subject); + message.setSentDate(new Date()); + message.setContent(finalString, type); + + if (log.isDebugEnabled()) { + log.debug("Meta data of the email configured successfully"); + } + Transport.send(message); + + if (log.isDebugEnabled()) { + log.debug("Mail sent to the EmailID" + " " + to + " " + "Successfully"); + } + } catch (MessagingException e) { + log.error("Error in sending the Email : " + smtpFromAddress.toString() + "::" +e.getMessage(), e); + } + } + + } +} diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/RegistryEventDispatcher.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/RegistryEventDispatcher.java index da1a0fad5..8dd11e6da 100644 --- a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/RegistryEventDispatcher.java +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/RegistryEventDispatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2005-2008,2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except @@ -32,9 +32,9 @@ import org.apache.axis2.context.MessageContext; import org.apache.axis2.transport.base.BaseConstants; import org.apache.axis2.transport.mail.MailConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.event.core.Message; import org.wso2.carbon.event.core.subscription.Subscription; import org.wso2.carbon.event.ws.internal.notify.WSEventDispatcher; @@ -42,24 +42,24 @@ import org.wso2.carbon.governance.notifications.worklist.stub.WorkListServiceStub; import org.wso2.carbon.registry.common.eventing.RegistryEvent; import org.wso2.carbon.registry.common.eventing.WorkListConfig; +import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.registry.eventing.events.DispatchEvent; +import org.wso2.carbon.registry.eventing.internal.EventingDataHolder; import org.wso2.carbon.registry.eventing.internal.JMXEventsBean; -import org.wso2.carbon.registry.eventing.internal.Utils; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.utils.CarbonUtils; +import javax.mail.Session; +import javax.mail.internet.InternetAddress; import javax.xml.namespace.QName; import java.io.Serializable; import java.rmi.RemoteException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; public class RegistryEventDispatcher extends WSEventDispatcher { @@ -71,6 +71,17 @@ public class RegistryEventDispatcher extends WSEventDispatcher { private static final Log log = LogFactory.getLog(RegistryEventDispatcher.class); + private static Session session; + private static ThreadPoolExecutor threadPoolExecutor; + private InternetAddress smtpFromAddress = null; + public static final int MIN_THREAD = 8; + public static final int MAX_THREAD = 100; + public static final String MIN_THREAD_NAME = "minThread"; + public static final String MAX_THREAD_NAME = "maxThread"; + public static final String DEFAULT_KEEP_ALIVE_TIME_NAME = "defaultKeepAliveTime"; + public static final long DEFAULT_KEEP_ALIVE_TIME = 20; + + private static WorkListConfig workListConfig = new WorkListConfig(); public static final class DigestEntry implements Serializable { @@ -235,8 +246,8 @@ public void notify(Message event, Subscription subscription) { if(endpoint.toLowerCase().contains("user://")){ try { String username = endpoint.substring(7); - if (Utils.getRegistryService() != null) { - UserRegistry registry = Utils.getRegistryService().getConfigSystemRegistry(); + if (EventingDataHolder.getInstance().getRegistryService() != null) { + UserRegistry registry = EventingDataHolder.getInstance().getRegistryService().getConfigSystemRegistry(); if (registry != null && registry.getUserRealm() != null && registry.getUserRealm().getUserStoreManager() != null) { UserStoreManager reader = registry.getUserRealm().getUserStoreManager(); @@ -256,8 +267,9 @@ else if(endpoint.toLowerCase().contains("role://")){ List emails = new LinkedList(); try { String roleName = endpoint.substring(7); - if (Utils.getRegistryService() != null) { - UserRegistry registry = Utils.getRegistryService().getConfigSystemRegistry(); + if (EventingDataHolder.getInstance().getRegistryService() != null) { + UserRegistry registry = + EventingDataHolder.getInstance().getRegistryService().getConfigSystemRegistry(); if (registry != null && registry.getUserRealm() != null && registry.getUserRealm().getUserStoreManager() != null) { UserStoreManager reader = registry.getUserRealm().getUserStoreManager(); @@ -300,9 +312,11 @@ else if(endpoint.toLowerCase().contains("role://")){ String email = null; try { String username = endpoint.substring(7); - if (Utils.getRegistryService() != null) { - UserRegistry registry = Utils.getRegistryService().getGovernanceSystemRegistry - (PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + if (EventingDataHolder.getInstance().getRegistryService() != null) { + UserRegistry registry = EventingDataHolder.getInstance().getRegistryService() + .getGovernanceSystemRegistry(PrivilegedCarbonContext + .getThreadLocalCarbonContext() + .getTenantId()); if (registry != null && registry.getUserRealm() != null && registry.getUserRealm().getUserStoreManager() != null) { UserStoreManager reader = registry.getUserRealm().getUserStoreManager(); @@ -321,9 +335,11 @@ else if(endpoint.toLowerCase().contains("role://")){ List emails = new LinkedList(); try { String roleName = endpoint.substring(7); - if (Utils.getRegistryService() != null) { - UserRegistry registry = Utils.getRegistryService().getGovernanceSystemRegistry - (PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + if (EventingDataHolder.getInstance().getRegistryService() != null) { + UserRegistry registry = EventingDataHolder.getInstance().getRegistryService() + .getGovernanceSystemRegistry(PrivilegedCarbonContext + .getThreadLocalCarbonContext() + .getTenantId()); if (registry != null && registry.getUserRealm() != null && registry.getUserRealm().getUserStoreManager() != null) { UserStoreManager reader = registry.getUserRealm().getUserStoreManager(); @@ -348,7 +364,7 @@ else if(endpoint.toLowerCase().contains("role://")){ } } else if (endpoint.toLowerCase().startsWith("jmx://")) { log.debug("Sending Notification to JMX endpoint"); - JMXEventsBean eventsBean = Utils.getEventsBean(); + JMXEventsBean eventsBean = EventingDataHolder.getInstance().getEventsBean(); if (eventsBean == null) { log.warn("Unable to generate notification. The notification bean has not been " + "registered."); @@ -408,7 +424,7 @@ private OMElement buildPayload(OMFactory factory, Message event, boolean isEmail // String poweredBy = "This message was automatically generated by WSO2 Carbon."; // String signature = "\n--\n" + poweredBy; String signature = ""; - String registryURL = Utils.getDefaultEventingServiceURL(); + String registryURL = EventingDataHolder.getInstance().getDefaultEventingServiceURL(); if (registryURL != null && registryURL.indexOf( "/services/RegistryEventingService") > -1) { registryURL = registryURL.substring(0, registryURL.length() - @@ -475,85 +491,125 @@ public void publishEvent(Message message, Subscription subscription, String endp } else { eventName = temp[2]; } - OMElement payload = buildPayload(factory, message, isEmail,eventName); + String emailMessage = null; + MimeEmailMessageHandler handler = new MimeEmailMessageHandler(); + if (message instanceof DispatchEvent && isEmail) { + emailMessage = handler.getEmailMessage(message); + } + String topicText = topicEle.getText(); + if (emailMessage != null && !emailMessage.equals(message.getMessage().toString())){ - if (endpoint != null) { - try { - if (doRest) { - if (configContext == null) { - MessageContext messageContext = MessageContext.getCurrentMessageContext(); - if (messageContext != null) { - configContext = messageContext.getConfigurationContext(); - } + String[] tTemp = topicText.split(RegistryEvent.TOPIC_SEPARATOR); + String event = ""; + if (tTemp[0].equals("")) { + event = tTemp[3]; + } else { + event = tTemp[2]; + } + String path = ""; + if (topicText.endsWith(RegistryEvent.TOPIC_SEPARATOR) || topicText.endsWith("*") || topicText.endsWith("#")) { + path = topicText.substring(RegistryEventingConstants.TOPIC_PREFIX.length()+event.length()+1, topicText.lastIndexOf(RegistryEvent.TOPIC_SEPARATOR)); + } else { + path = topicText.substring(RegistryEventingConstants.TOPIC_PREFIX.length()+event.length()+1); + } + String mailSubject = handler.getEmailSubject(message, path, event); + try{ + if (configContext == null) { + MessageContext messageContext = MessageContext.getCurrentMessageContext(); + if (messageContext != null) { + configContext = messageContext.getConfigurationContext(); } + } + handler.sendMimeMessage(configContext, emailMessage, mailSubject,endpoint.replace("mailto:","") ); + } catch (RegistryException e) { + log.error("Unable to send email notifications", e); + } - ServiceClient serviceClient; - if (configContext != null) { - serviceClient = new ServiceClient(configContext, null); - } else { - serviceClient = new ServiceClient(); - } - Options options = new Options(); - serviceClient.engageModule("addressing"); - options.setTo(new EndpointReference(endpoint)); - options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); - if (endpoint.toLowerCase().startsWith("mailto:")) { - Map headerMap = new HashMap(); - String topicText = topicEle.getText(); - if (topicText != null && topicText.lastIndexOf("/") > 0) { - String[] tTemp = topicText.split(RegistryEvent.TOPIC_SEPARATOR); - String event = ""; - if (tTemp[0].equals("")) { - event = tTemp[3]; - } else { - event = tTemp[2]; - } - String path = ""; - if (topicText.endsWith(RegistryEvent.TOPIC_SEPARATOR) || topicText.endsWith("*") || topicText.endsWith("#")) { - path = topicText - .substring(RegistryEventingConstants.TOPIC_PREFIX.length()+event.length()+1, - topicText.lastIndexOf(RegistryEvent.TOPIC_SEPARATOR)); - } else { - path = topicText - .substring(RegistryEventingConstants.TOPIC_PREFIX.length()+event.length()+1); + } else { + OMElement payload = buildPayload(factory, message, isEmail, eventName); + + if (endpoint != null) { + try { + if (doRest) { + if (configContext == null) { + MessageContext messageContext = MessageContext.getCurrentMessageContext(); + if (messageContext != null) { + configContext = messageContext.getConfigurationContext(); } + } + + ServiceClient serviceClient; + if (configContext != null) { + serviceClient = new ServiceClient(configContext, null); + } else { + serviceClient = new ServiceClient(); + } + Options options = new Options(); + serviceClient.engageModule("addressing"); + options.setTo(new EndpointReference(endpoint)); + options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); + if (endpoint.toLowerCase().startsWith("mailto:")) { + Map headerMap = new HashMap(); + if (topicText != null && topicText.lastIndexOf("/") > 0) { + String[] tTemp = topicText.split(RegistryEvent.TOPIC_SEPARATOR); + String event = ""; + if (tTemp[0].equals("")) { + event = tTemp[3]; + } else { + event = tTemp[2]; + } + String path = ""; + if (topicText.endsWith(RegistryEvent.TOPIC_SEPARATOR) || topicText.endsWith("*") || topicText.endsWith("#")) { + path = topicText + .substring(RegistryEventingConstants.TOPIC_PREFIX.length()+event.length()+1, + topicText.lastIndexOf(RegistryEvent.TOPIC_SEPARATOR)); + } else { + path = topicText + .substring(RegistryEventingConstants.TOPIC_PREFIX.length()+event.length()+1); + } + + String mailHeader = message.getProperty(MailConstants.MAIL_HEADER_SUBJECT); + if (mailHeader != null) { + headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, mailHeader); + } else if (path == null || path.length() == 0) { + headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, + "[" + event + "]"); + } else { + headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, + "[" + event + "] at path: " + path); + } + headerMap.put(MailConstants.TRANSPORT_MAIL_FORMAT, "text/html"); + headerMap.put(MailConstants.TRANSPORT_MAIL_CONTENT_TYPE, "text/html"); - String mailHeader = message.getProperty(MailConstants.MAIL_HEADER_SUBJECT); - if (mailHeader != null) { - headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, mailHeader); - } else if (path == null || path.length() == 0) { - headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, - "[" + event + "]"); - } else { - headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, - "[" + event + "] at path: " + path); } + options.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); + //options.setProperty(MailConstants.TRANSPORT_MAIL_FORMAT, + // MailConstants.TRANSPORT_FORMAT_TEXT); + options.setProperty(MailConstants.TRANSPORT_MAIL_FORMAT, "text/html"); + options.setProperty(MailConstants.TRANSPORT_MAIL_CONTENT_TYPE, "text/html"); } - options.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); - options.setProperty(MailConstants.TRANSPORT_MAIL_FORMAT, - MailConstants.TRANSPORT_FORMAT_TEXT); - } - options.setProperty(MessageContext.CLIENT_API_NON_BLOCKING, Boolean.TRUE); - options.setAction(RegistryEventingConstants.WSE_PUBLISH); - serviceClient.setOptions(options); - if(log.isDebugEnabled()){ - log.debug("\nThe payload contains in the publishing event is : \n" + payload.toString()); - } - serviceClient.fireAndForget(payload); - } else { - if(log.isDebugEnabled()){ - log.debug("\nThe payload contains in the publishing event is : \n" + payload.toString()); + options.setProperty(MessageContext.CLIENT_API_NON_BLOCKING, Boolean.TRUE); + options.setAction(RegistryEventingConstants.WSE_PUBLISH); + serviceClient.setOptions(options); + if(log.isDebugEnabled()){ + log.debug("\nThe payload contains in the publishing event is : \n" + payload.toString()); + } + serviceClient.fireAndForget(payload); + } else { + if(log.isDebugEnabled()){ + log.debug("\nThe payload contains in the publishing event is : \n" + payload.toString()); + } + super.sendNotification(topicEle, payload, endpoint); } - super.sendNotification(topicEle, payload, endpoint); + } catch (AxisFault e) { + log.error("Unable to send message", e); } - } catch (AxisFault e) { - log.error("Unable to send message", e); } } } public String getEndpoint() { - return Utils.getDefaultEventingServiceURL(); + return EventingDataHolder.getInstance().getDefaultEventingServiceURL(); } private void addToEmailDigestQueue(Message event, String topic, String endpoint, String digestType, diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/events/DispatchEvent.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/events/DispatchEvent.java index 037c4cfb1..ac88ba8bc 100644 --- a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/events/DispatchEvent.java +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/events/DispatchEvent.java @@ -200,4 +200,8 @@ public String getTopic() { public Map getParameters() { return event.getParameters(); } + + public RegistryEvent getEvent(){ + return event; + } } diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/handlers/RegistryEventingHandler.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/handlers/RegistryEventingHandler.java index c9ad80200..e56af6181 100644 --- a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/handlers/RegistryEventingHandler.java +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/handlers/RegistryEventingHandler.java @@ -33,7 +33,7 @@ import org.wso2.carbon.registry.core.session.CurrentSession; import org.wso2.carbon.registry.core.utils.RegistryUtils; import org.wso2.carbon.registry.eventing.events.*; -import org.wso2.carbon.registry.eventing.internal.Utils; +import org.wso2.carbon.registry.eventing.internal.EventingDataHolder; import java.util.List; @@ -422,7 +422,8 @@ public void putChild(RequestContext requestContext) throws RegistryException { childCreatedEvent.setParameter("ChildPath", relativePath); ((ChildCreatedEvent)childCreatedEvent).setResourcePath(parentPath); } else { - childCreatedEvent = new ChildCreatedEvent("A collection was added to the collection " + parentPath + " at Path: " + relativePath); + childCreatedEvent = new ChildCreatedEvent( + "A collection was added to the collection " + parentPath + " at Path: " + relativePath); childCreatedEvent.setParameter("ChildPath", relativePath); ((ChildCreatedEvent)childCreatedEvent).setResourcePath(parentPath); } @@ -699,20 +700,22 @@ public void restore(RequestContext requestContext) throws RegistryException { protected void notify(RegistryEvent event, Registry registry, String path) throws Exception { try { - if (Utils.getRegistryEventingService() == null) { + if (EventingDataHolder.getInstance().getRegistryEventingService() == null) { log.debug("Eventing service is unavailable."); return; } if (registry == null || registry.getEventingServiceURL(path) == null) { - Utils.getRegistryEventingService().notify(event); + EventingDataHolder.getInstance().getRegistryEventingService().notify(event); return; - } else if (Utils.getDefaultEventingServiceURL() == null) { + } else if (EventingDataHolder.getInstance().getDefaultEventingServiceURL() == null) { log.error("Registry Eventing Handler is not properly initialized"); - } else if (registry.getEventingServiceURL(path).equals(Utils.getDefaultEventingServiceURL())) { - Utils.getRegistryEventingService().notify(event); + } else if (registry.getEventingServiceURL(path) + .equals(EventingDataHolder.getInstance().getDefaultEventingServiceURL())) { + EventingDataHolder.getInstance().getRegistryEventingService().notify(event); return; } else { - Utils.getRegistryEventingService().notify(event, registry.getEventingServiceURL(path)); + EventingDataHolder.getInstance().getRegistryEventingService() + .notify(event, registry.getEventingServiceURL(path)); return; } } catch (RegistryException e) { @@ -728,16 +731,22 @@ private void handleException(String message, Exception e) { /** * Method to get the actual depth of the request + * @param requestContext Request Context */ private int getRequestDepth(RequestContext requestContext){ int requestDepth = -1; - if(requestContext.getRegistry().getRegistryContext() != null && requestContext.getRegistry().getRegistryContext().getDataAccessManager() != null && requestContext.getRegistry().getRegistryContext().getDataAccessManager().getDatabaseTransaction() != null){ - requestDepth = requestContext.getRegistry().getRegistryContext().getDataAccessManager().getDatabaseTransaction().getNestedDepth(); + if (requestContext.getRegistry().getRegistryContext() != null && + requestContext.getRegistry().getRegistryContext().getDataAccessManager() != null && + requestContext.getRegistry().getRegistryContext().getDataAccessManager().getDatabaseTransaction() != null) { + requestDepth = + requestContext.getRegistry().getRegistryContext().getDataAccessManager().getDatabaseTransaction() + .getNestedDepth(); } return requestDepth; } private boolean sendNotifications(RequestContext requestContext, String relativePath){ + boolean isMountPath = false; List mounts = requestContext.getRegistry().getRegistryContext().getMounts(); for (Mount mount: mounts) { diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/handlers/erbsm/EmbeddedRegistryBasedSubscriptionManagerResourceRelocateHandler.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/handlers/erbsm/EmbeddedRegistryBasedSubscriptionManagerResourceRelocateHandler.java index 095392892..75c7d5a7f 100644 --- a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/handlers/erbsm/EmbeddedRegistryBasedSubscriptionManagerResourceRelocateHandler.java +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/handlers/erbsm/EmbeddedRegistryBasedSubscriptionManagerResourceRelocateHandler.java @@ -26,7 +26,6 @@ import org.wso2.carbon.registry.core.utils.RegistryUtils; import org.wso2.carbon.registry.eventing.RegistryEventingConstants; import org.wso2.carbon.registry.eventing.handlers.SubscriptionManagerHandler; -import org.wso2.carbon.registry.eventing.internal.Utils; import org.apache.axiom.om.util.UUIDGenerator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/EventingDataHolder.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/EventingDataHolder.java new file mode 100644 index 000000000..3ef594df2 --- /dev/null +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/EventingDataHolder.java @@ -0,0 +1,128 @@ +/* +* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package org.wso2.carbon.registry.eventing.internal; + +import org.apache.axis2.context.ConfigurationContext; +import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber; +import org.wso2.carbon.email.verification.util.EmailVerifierConfig; +import org.wso2.carbon.event.core.EventBroker; +import org.wso2.carbon.registry.core.service.RegistryService; +import org.wso2.carbon.registry.eventing.services.EventingService; + +public class EventingDataHolder { + + private static EventingDataHolder holder = new EventingDataHolder(); + + private EventingDataHolder(){ + } + + public static EventingDataHolder getInstance(){ + return holder; + } + + private RegistryService registryService; + + private String defaultEventingServiceURL; + + private EventingService registryEventingService; + + private EventBroker registryEventBrokerService; + + private ConfigurationContext configurationContext; + + private EmailVerifcationSubscriber emailVerificationSubscriber; + + private EmailVerifierConfig emailVerifierConfig = null; + + private JMXEventsBean eventsBean; + + private NotificationConfig notificationConfig; + + public RegistryService getRegistryService() { + return registryService; + } + + public void setRegistryService(RegistryService registryService) { + this.registryService = registryService; + } + + public String getDefaultEventingServiceURL() { + return defaultEventingServiceURL; + } + + public void setDefaultEventingServiceURL(String defaultEventingServiceURL) { + this.defaultEventingServiceURL = defaultEventingServiceURL; + } + + public EventingService getRegistryEventingService() { + return registryEventingService; + } + + public void setRegistryEventingService(EventingService registryEventingService) { + this.registryEventingService = registryEventingService; + } + + public EventBroker getRegistryEventBrokerService() { + return registryEventBrokerService; + } + + public void setRegistryEventBrokerService(EventBroker registryEventBrokerService) { + this.registryEventBrokerService = registryEventBrokerService; + } + + public ConfigurationContext getConfigurationContext() { + return configurationContext; + } + + public void setConfigurationContext(ConfigurationContext configurationContext) { + this.configurationContext = configurationContext; + } + + public EmailVerifcationSubscriber getEmailVerificationSubscriber() { + return emailVerificationSubscriber; + } + + public void setEmailVerificationSubscriber(EmailVerifcationSubscriber emailVerificationSubscriber) { + this.emailVerificationSubscriber = emailVerificationSubscriber; + } + + public EmailVerifierConfig getEmailVerifierConfig() { + return emailVerifierConfig; + } + + public void setEmailVerifierConfig(EmailVerifierConfig emailVerifierConfig) { + this.emailVerifierConfig = emailVerifierConfig; + } + + public JMXEventsBean getEventsBean() { + return eventsBean; + } + + public void setEventsBean(JMXEventsBean eventsBean) { + this.eventsBean = eventsBean; + } + + public NotificationConfig getNotificationConfig() { + return notificationConfig; + } + + public void setNotificationConfig(NotificationConfig notificationConfig) { + this.notificationConfig = notificationConfig; + } +} diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/NotificationConfig.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/NotificationConfig.java new file mode 100644 index 000000000..8a95421ed --- /dev/null +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/NotificationConfig.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2015 WSO2 Inc. (http://wso2.com) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.registry.eventing.internal; + + +public class NotificationConfig { + + private String configurationClass; + + private String storeURL; + + private String publisherURL; + + private String consoleURL; + + public String getConfigurationClass() { + return configurationClass; + } + + public void setConfigurationClass(String configurationClass) { + this.configurationClass = configurationClass; + } + + public String getStoreURL() { + return storeURL; + } + + public void setStoreURL(String storeURL) { + this.storeURL = storeURL; + } + + public String getPublisherURL() { + return publisherURL; + } + + public void setPublisherURL(String publisherURL) { + this.publisherURL = publisherURL; + } + + public String getConsoleURL() { + return consoleURL; + } + + public void setConsoleURL(String consoleURL) { + this.consoleURL = consoleURL; + } +} diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/RegistryEventingServiceComponent.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/RegistryEventingServiceComponent.java index 49d2cdc31..8986f1dbd 100644 --- a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/RegistryEventingServiceComponent.java +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/RegistryEventingServiceComponent.java @@ -22,6 +22,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.axis2.context.ConfigurationContext; +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.engine.ListenerManager; import org.apache.axis2.addressing.EndpointReference; @@ -55,6 +59,12 @@ import java.io.File; import java.net.SocketException; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; +import java.io.File; +import java.io.FileInputStream; +import java.util.*; /** * @scr.component name="org.wso2.carbon.registry.eventing" immediate="true" @@ -104,6 +114,8 @@ public class RegistryEventingServiceComponent { private String eventingRoot = "/repository/components/org.wso2.carbon.event/"; + private String defaultClass = "org.wso2.carbon.registry.eventing.template.RegistryNotification"; + protected void activate(ComponentContext context) { bundleContext = context.getBundleContext(); initialize(); @@ -118,14 +130,14 @@ private void registerEventingService() { notificationServiceRegistration = bundleContext.registerService(NotificationService.class.getName(), service, null); emailVerificationServiceRegistration = bundleContext.registerService( SubscriptionEmailVerficationService.class.getName(), service, null); - Utils.setRegistryEventingService(service); + EventingDataHolder.getInstance().setRegistryEventingService(service); log.debug("Successfully setup the Eventing OGSi Service"); } } private void unregisterEventingService() { if (eventingServiceRegistration != null) { - Utils.setRegistryEventingService(null); + EventingDataHolder.getInstance().setRegistryEventingService(null); eventingServiceRegistration.unregister(); eventingServiceRegistration = null; notificationServiceRegistration.unregister(); @@ -146,23 +158,23 @@ protected void setConfigurationContextService(ConfigurationContextService config log.debug("The Configuration Context Service was set"); this.configurationContextService = configurationContextService; if (configurationContextService != null) { - Utils.setConfigurationContext(configurationContextService.getServerConfigContext()); + EventingDataHolder.getInstance().setConfigurationContext(configurationContextService.getServerConfigContext()); } } protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { - Utils.setConfigurationContext(null); + EventingDataHolder.getInstance().setConfigurationContext(null); } protected void setRegistryService(RegistryService registryService) { - Utils.setRegistryService(registryService); + EventingDataHolder.getInstance().setRegistryService(registryService); } private void setupEmailVerification() { - if (Utils.getEmailVerificationSubscriber() == null) { + if (EventingDataHolder.getInstance().getEmailVerificationSubscriber() == null) { return; } - EmailVerifierConfig emailVerifierConfig = Utils.getEmailVerifierConfig(); + EmailVerifierConfig emailVerifierConfig = EventingDataHolder.getInstance().getEmailVerifierConfig(); if (emailVerifierConfig == null) { String fileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + "notifications-email-verification.xml"; @@ -181,7 +193,7 @@ private void setupEmailVerification() { "by the WSO2 Carbon Registry."); } if (emailVerifierConfig.getTargetEpr() == null) { - String registryURL = Utils.getDefaultEventingServiceURL(); + String registryURL = EventingDataHolder.getInstance().getDefaultEventingServiceURL(); if (registryURL != null && registryURL.indexOf( "/services/RegistryEventingService") > -1) { registryURL = registryURL.substring(0, registryURL.length() - @@ -206,28 +218,94 @@ private void setupEmailVerification() { emailVerifierConfig.setRedirectPath("../info/subscription-email-verified.jsp"); } log.debug("The E-mail Verfication Component Configuration has been done."); - Utils.setEmailVerifierConfig(emailVerifierConfig); + EventingDataHolder.getInstance().setEmailVerifierConfig(emailVerifierConfig); } } protected void unsetEmailVerificationSubscriber(EmailVerifcationSubscriber emailVerificationSubscriber) { - Utils.setEmailVerificationSubscriber(null); + EventingDataHolder.getInstance().setEmailVerificationSubscriber(null); } protected void setEmailVerificationSubscriber(EmailVerifcationSubscriber emailVerificationSubscriber) { - Utils.setEmailVerificationSubscriber(emailVerificationSubscriber); + EventingDataHolder.getInstance().setEmailVerificationSubscriber(emailVerificationSubscriber); + } + + private void setSubscriptionConfiguration(){ + NotificationConfig config = new NotificationConfig(); + String fileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + "registry.xml"; + if ((new File(fileName)).exists()) { + config = loadeNotificationConfig(fileName); + } + if (config == null) { + config = new NotificationConfig(); + } + String serverURL = EventingDataHolder.getInstance().getDefaultEventingServiceURL(); + if (serverURL != null && serverURL.indexOf( + "/services/RegistryEventingService") > -1) { + serverURL = serverURL.substring(0, serverURL.length() -"/services/RegistryEventingService".length()); + } + if (config.getConfigurationClass() == null) { + config.setConfigurationClass(defaultClass); + } + if (config.getStoreURL() == null){ + config.setStoreURL(serverURL+"/store"); + } + if (config.getPublisherURL() == null){ + config.setPublisherURL(serverURL+"/publisher"); + } + if (config.getConsoleURL() == null) { + config.setConsoleURL(serverURL+"/carbon"); + } + EventingDataHolder.getInstance().setNotificationConfig(config); + + } + + private NotificationConfig loadeNotificationConfig(String configFilename) { + NotificationConfig config = new NotificationConfig(); + File configFile = new File(configFilename); + if (!configFile.exists()) { + log.error("Configuration File is not present at: " + configFilename); + return null; + } + try { + XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader( new FileInputStream(configFile)); + StAXOMBuilder builder = new StAXOMBuilder(parser); + OMElement documentElement = builder.getDocumentElement(); + OMElement notificationConfig = documentElement.getFirstChildWithName(new QName("notificationConfiguration")); + if (notificationConfig != null) { //registry.xml need an entry to continue + Iterator it = notificationConfig.getChildElements(); + while (it.hasNext()) { + OMElement element = (OMElement) it.next(); + if ("class".equals(element.getLocalName())) { + config.setConfigurationClass(element.getText()); + } else if ("storeURL".equals(element.getLocalName())) { + config.setStoreURL(element.getText()); + } else if ("publisherURL".equals(element.getLocalName())) { + config.setPublisherURL(element.getText()); + } else if ("consoleURL".equals(element.getLocalName())) { + config.setConsoleURL(element.getText()); + } + } + } + return config; + } catch (Exception e) { + String msg = "Error in loading configuration : " + + configFilename + "."; + log.error(msg, e); + return null; + } } protected void unsetRegistryService(RegistryService registryService) { - Utils.setRegistryService(null); + EventingDataHolder.getInstance().setRegistryService(null); } protected void setEventBroker(EventBroker eventBroker) { - Utils.setRegistryEventBrokerService(eventBroker); + EventingDataHolder.getInstance().setRegistryEventBrokerService(eventBroker); } protected void unsetEventBroker(EventBroker eventBroker) { - Utils.setRegistryEventBrokerService(null); + EventingDataHolder.getInstance().setRegistryEventBrokerService(null); } protected void setListenerManager(ListenerManager listenerManager) { @@ -239,11 +317,11 @@ protected void setListenerManager(ListenerManager listenerManager) { protected void setEvents(Events notifications) { JMXEventsBean implBean = new JMXEventsBean(); notifications.setImplBean(implBean); - Utils.setEventsBean(implBean); + EventingDataHolder.getInstance().setEventsBean(implBean); } protected void unsetEvents(Events notifications) { - Utils.setEventsBean(null); + EventingDataHolder.getInstance().setEventsBean(null); notifications.setImplBean(null); } @@ -254,7 +332,8 @@ protected void unsetListenerManager(ListenerManager listenerManager) { private void initialize() { ConfigurationContext serverConfigurationContext = configurationContextService.getServerConfigContext(); - if (!configurationDone && listenerManager != null && Utils.getRegistryService() != null) { + if (!configurationDone && listenerManager != null && + EventingDataHolder.getInstance().getRegistryService() != null) { String host; try { host = NetworkUtils.getLocalHostname(); @@ -352,6 +431,7 @@ private void initialize() { setupHandlers(); setupDispatchers(); setupEmailVerification(); + setSubscriptionConfiguration(); log.debug("Successfully instantiated the Registry Event Source"); } catch (Exception e) { String msg = "Error Instantiating Registry Event Source"; @@ -366,9 +446,9 @@ private void initialize() { // available. private void setupDispatchers() throws Exception { RegistryEventDispatcher dispatcher = new RegistryEventDispatcher(); - dispatcher.init(Utils.getConfigurationContext()); - if (Utils.getRegistryEventBrokerService() != null) { - Utils.getRegistryEventBrokerService().registerEventDispatcher( + dispatcher.init(EventingDataHolder.getInstance().getConfigurationContext()); + if (EventingDataHolder.getInstance().getRegistryEventBrokerService() != null) { + EventingDataHolder.getInstance().getRegistryEventBrokerService().registerEventDispatcher( RegistryEventingConstants.TOPIC_PREFIX, dispatcher); } } @@ -380,7 +460,7 @@ private void setupHandlers() { "generated unless a custom handler has been configured."); return; } - RegistryService registryService = Utils.getRegistryService(); + RegistryService registryService = EventingDataHolder.getInstance().getRegistryService(); if (registryService instanceof RemoteRegistryService && !initialized) { initialized = true; log.warn("Eventing is not available on Remote Registry"); @@ -423,7 +503,7 @@ private void setupHandlers() { registry.getRegistryContext().getHandlerManager().addHandler(null, filter, handler, HandlerLifecycleManager.DEFAULT_REPORTING_HANDLER_PHASE); registry.setEventingServiceURL(null, endpoint); - Utils.setDefaultEventingServiceURL(endpoint); + EventingDataHolder.getInstance().setDefaultEventingServiceURL(endpoint); log.debug("Successfully Initialized the Registry Eventing Handler"); /*URLMatcher erbSubManagerMountFilter = new URLMatcher(); diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/Utils.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/Utils.java deleted file mode 100644 index 6cc68e4fa..000000000 --- a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/internal/Utils.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.wso2.carbon.registry.eventing.internal; - -import org.apache.axis2.context.ConfigurationContext; -import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber; -import org.wso2.carbon.email.verification.util.EmailVerifierConfig; -import org.wso2.carbon.event.core.EventBroker; -import org.wso2.carbon.registry.core.service.RegistryService; -import org.wso2.carbon.registry.eventing.services.EventingService; - -public class Utils { - private static RegistryService registryService; - - private static String defaultEventingServiceURL; - - private static EventingService registryEventingService; - - private static EventBroker registryEventBrokerService; - - private static ConfigurationContext configurationContext; - - private static EmailVerifcationSubscriber emailVerificationSubscriber; - - private static EmailVerifierConfig emailVerifierConfig = null; - - private static JMXEventsBean eventsBean; - - public static synchronized void setRegistryService(RegistryService service) { - registryService = service; - } - - public static synchronized RegistryService getRegistryService() { - return registryService; - } - - public static String getDefaultEventingServiceURL() { - return defaultEventingServiceURL; - } - - public static void setDefaultEventingServiceURL(String defaultEventingServiceURL) { - Utils.defaultEventingServiceURL = defaultEventingServiceURL; - } - - public static EventingService getRegistryEventingService() { - return registryEventingService; - } - - public static void setRegistryEventingService(EventingService registryEventingService) { - Utils.registryEventingService = registryEventingService; - } - - public static EventBroker getRegistryEventBrokerService() { - return registryEventBrokerService; - } - - public static void setRegistryEventBrokerService(EventBroker registryEventBrokerService) { - Utils.registryEventBrokerService = registryEventBrokerService; - } - - public static ConfigurationContext getConfigurationContext() { - return configurationContext; - } - - public static void setConfigurationContext(ConfigurationContext configurationContext) { - Utils.configurationContext = configurationContext; - } - - public static EmailVerifcationSubscriber getEmailVerificationSubscriber() { - return emailVerificationSubscriber; - } - - public static void setEmailVerificationSubscriber( - EmailVerifcationSubscriber emailVerificationSubscriber) { - Utils.emailVerificationSubscriber = emailVerificationSubscriber; - } - - public static EmailVerifierConfig getEmailVerifierConfig() { - return emailVerifierConfig; - } - - public static void setEmailVerifierConfig(EmailVerifierConfig emailVerifierConfig) { - Utils.emailVerifierConfig = emailVerifierConfig; - } - - public static JMXEventsBean getEventsBean() { - return eventsBean; - } - - public static void setEventsBean(JMXEventsBean eventsBean) { - Utils.eventsBean = eventsBean; - } -} diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/services/EventingServiceImpl.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/services/EventingServiceImpl.java index 2e7861a67..5b02d41fb 100644 --- a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/services/EventingServiceImpl.java +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/services/EventingServiceImpl.java @@ -35,7 +35,7 @@ import org.wso2.carbon.registry.eventing.RegistryEventDispatcher; import org.wso2.carbon.registry.eventing.RegistryEventingConstants; import org.wso2.carbon.registry.eventing.events.*; -import org.wso2.carbon.registry.eventing.internal.Utils; +import org.wso2.carbon.registry.eventing.internal.EventingDataHolder; import javax.xml.stream.XMLStreamException; import java.util.*; @@ -94,7 +94,7 @@ public String verifyEmail(String data) { // The updated subscription should be directly done at the subMgr to avoid // generating another verification request subscription.setId(subscriptionId); - Utils.getRegistryEventBrokerService().renewSubscription(subscription); + EventingDataHolder.getInstance().getRegistryEventBrokerService().renewSubscription(subscription); } return email; } catch (Exception e) { @@ -137,7 +137,7 @@ public void notify(RegistryEvent event, String endpoint) throws Exception { private synchronized static void initializeDispatcher() { if (dispatcher == null) { dispatcher = new RegistryEventDispatcher(); - ((RegistryEventDispatcher)dispatcher).init(Utils.getConfigurationContext()); + ((RegistryEventDispatcher)dispatcher).init(EventingDataHolder.getInstance().getConfigurationContext()); } } @@ -171,7 +171,7 @@ public void registerEventType(String typeId, String resourceEvent, String collec } public List getAllSubscriptions() throws EventBrokerException { - return Utils.getRegistryEventBrokerService().getAllSubscriptions(null); + return EventingDataHolder.getInstance().getRegistryEventBrokerService().getAllSubscriptions(null); } public List getAllSubscriptions(String userName, String remoteURL) @@ -184,16 +184,18 @@ public Map getEventTypes() { } public String getSubscriptionManagerUrl() { - return Utils.getDefaultEventingServiceURL(); + return EventingDataHolder.getInstance().getDefaultEventingServiceURL(); } public Subscription getSubscription(String id) { try { - if(id != null && id.contains(";version:")) { - log.warn("Versioned resources cannot have subscriptions, instead returns the subscription from the actual resource"); - return Utils.getRegistryEventBrokerService().getSubscription(RegistryUtil.getResourcePathFromVersionPath(id)); + if (id != null && id.contains(";version:")) { + log.warn( + "Versioned resources cannot have subscriptions, instead returns the subscription from the actual resource"); + return EventingDataHolder.getInstance().getRegistryEventBrokerService() + .getSubscription(RegistryUtil.getResourcePathFromVersionPath(id)); } else { - return Utils.getRegistryEventBrokerService().getSubscription(id); + return EventingDataHolder.getInstance().getRegistryEventBrokerService().getSubscription(id); } } catch (EventBrokerException e) { log.error("Unable to get subscription for given id: " + id, e); @@ -233,7 +235,7 @@ public String subscribe(Subscription subscription) { Boolean.toString(true)); subscription.setProperties(subscriptionData); } - String subscribe = Utils.getRegistryEventBrokerService().subscribe(subscription); + String subscribe = EventingDataHolder.getInstance().getRegistryEventBrokerService().subscribe(subscription); requestEmailVerification(subscription, null, null); return subscribe; } catch (EventBrokerException e) { @@ -249,7 +251,7 @@ private boolean isEmailAlreadyAvailable(Subscription subscription) { String email = subscription.getEventSinkURL().substring(subscription.getEventSinkURL().indexOf(":") + 1 , subscription.getEventSinkURL().length()); try { - UserRegistry registry = Utils.getRegistryService().getConfigSystemRegistry(); + UserRegistry registry = EventingDataHolder.getInstance().getRegistryService().getConfigSystemRegistry(); String emailIndexPath = this.emailIndexStoragePath; Resource emailIndexResource; if (registry.resourceExists(emailIndexPath)) { @@ -278,7 +280,7 @@ public Subscription getSubscription(String id, String userName, String remoteURL public boolean unsubscribe(String subscriptionID) { try { - Utils.getRegistryEventBrokerService().unsubscribe(subscriptionID); + EventingDataHolder.getInstance().getRegistryEventBrokerService().unsubscribe(subscriptionID); return true; } catch (EventBrokerException e) { log.error("Unable to unsubscribe using given id: " + subscriptionID, e); @@ -337,7 +339,7 @@ public EmailVerifier(Subscription subscription, String userName, String remoteUR public void run() { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); - if (Utils.getEmailVerificationSubscriber() == null) { + if (EventingDataHolder.getInstance().getEmailVerificationSubscriber() == null) { return; } String eventUrl = subscription.getEventSinkURL(); @@ -366,8 +368,8 @@ else if(lowerCasedEventUrl.contains("mailto:")) { data.put("remoteURL", remoteURL); } try { - Utils.getEmailVerificationSubscriber().requestUserVerification(data, - Utils.getEmailVerifierConfig()); + EventingDataHolder.getInstance().getEmailVerificationSubscriber().requestUserVerification(data, + EventingDataHolder.getInstance().getEmailVerifierConfig()); } catch (Exception e) { log.error("Unable to create e-mail verification request", e); } @@ -406,23 +408,27 @@ public void run() { // For each resource-event also generate a corresponding collection event, so that any hierarchical subscriptions would // work. if (event.getTopic().contains(ResourceUpdatedEvent.EVENT_NAME)) { - Utils.getRegistryEventBrokerService().publish(event, event.getTopic()); - Utils.getRegistryEventBrokerService().publish(event, event.getTopic().replace( - ResourceUpdatedEvent.EVENT_NAME, CollectionUpdatedEvent.EVENT_NAME)); + EventingDataHolder.getInstance().getRegistryEventBrokerService() + .publish(event, event.getTopic()); + EventingDataHolder.getInstance().getRegistryEventBrokerService().publish(event, event.getTopic() + .replace(ResourceUpdatedEvent.EVENT_NAME, CollectionUpdatedEvent.EVENT_NAME)); } else if (event.getTopic().contains(ResourceAddedEvent.EVENT_NAME)) { - Utils.getRegistryEventBrokerService().publish(event, event.getTopic()); - Utils.getRegistryEventBrokerService().publish(event, event.getTopic().replace( - ResourceAddedEvent.EVENT_NAME, CollectionAddedEvent.EVENT_NAME)); + EventingDataHolder.getInstance().getRegistryEventBrokerService() + .publish(event, event.getTopic()); + EventingDataHolder.getInstance().getRegistryEventBrokerService().publish(event, event.getTopic() + .replace(ResourceAddedEvent.EVENT_NAME, CollectionAddedEvent.EVENT_NAME)); } else if (event.getTopic().contains(ResourceCreatedEvent.EVENT_NAME)) { - Utils.getRegistryEventBrokerService().publish(event, event.getTopic()); - Utils.getRegistryEventBrokerService().publish(event, event.getTopic().replace( - ResourceCreatedEvent.EVENT_NAME, CollectionCreatedEvent.EVENT_NAME)); + EventingDataHolder.getInstance().getRegistryEventBrokerService() + .publish(event, event.getTopic()); + EventingDataHolder.getInstance().getRegistryEventBrokerService().publish(event, event.getTopic() + .replace(ResourceCreatedEvent.EVENT_NAME, CollectionCreatedEvent.EVENT_NAME)); } else if (event.getTopic().contains(ResourceDeletedEvent.EVENT_NAME)) { - Utils.getRegistryEventBrokerService().publish(event, event.getTopic()); - Utils.getRegistryEventBrokerService().publish(event, event.getTopic().replace( - ResourceDeletedEvent.EVENT_NAME, CollectionDeletedEvent.EVENT_NAME)); + EventingDataHolder.getInstance().getRegistryEventBrokerService().publish(event, event.getTopic()); + EventingDataHolder.getInstance().getRegistryEventBrokerService().publish(event, event.getTopic() + .replace(ResourceDeletedEvent.EVENT_NAME, CollectionDeletedEvent.EVENT_NAME)); } else { - Utils.getRegistryEventBrokerService().publish(event, event.getTopic()); + EventingDataHolder.getInstance().getRegistryEventBrokerService() + .publish(event, event.getTopic()); } } finally { PrivilegedCarbonContext.endTenantFlow(); diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/template/NotificationTemplate.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/template/NotificationTemplate.java new file mode 100644 index 000000000..98c87040c --- /dev/null +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/template/NotificationTemplate.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.registry.eventing.template; + +import org.wso2.carbon.registry.core.Registry; + +public interface NotificationTemplate { + + /** + * This method used to populate email message body. + * + * @param configRegistry Configuration Registry + * @param resourcePath Registry Resource Path + * @param message Current + * @param eventType Eventing type + * @return Populated email message body + */ + public String populateEmailMessage(Registry configRegistry,String resourcePath, String message, String eventType); + +} diff --git a/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/template/RegistryNotification.java b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/template/RegistryNotification.java new file mode 100644 index 000000000..7a706f6e6 --- /dev/null +++ b/components/registry/org.wso2.carbon.registry.eventing/src/main/java/org/wso2/carbon/registry/eventing/template/RegistryNotification.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.registry.eventing.template; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.registry.core.Registry; +import org.wso2.carbon.registry.core.Resource; +import org.wso2.carbon.registry.core.exceptions.RegistryException; + + +public class RegistryNotification implements NotificationTemplate { + + private static final String TEMPLATE_PATH = "/repository/components/org.wso2.carbon.governance/templates"; + private static final String DEFAULT_TEMPLATE_NAME = "default"; + private static final String TEMPLATE_EXT = ".html"; + private static final String DEFAULT_TEMPLATE = TEMPLATE_PATH + "/"+DEFAULT_TEMPLATE_NAME+TEMPLATE_EXT; + + + private static final Log log = LogFactory.getLog(RegistryNotification.class); + + /** + * This method used to populate email message body. As default behavior this will replace the $$message$$ content + * of the template using input message. + * + * @param configRegistry Configuration Registry + * @param resourcePath Registry Resource Path + * @param message Current + * @param eventType Eventing type + * @return Populated email message body + */ + public String populateEmailMessage(Registry configRegistry,String resourcePath,String message, String eventType) { + String templateLocation = TEMPLATE_PATH +"/"+eventType.toLowerCase() +TEMPLATE_EXT; + Resource template = null; + try { + if (configRegistry.resourceExists(templateLocation)){ + template = configRegistry.get(templateLocation); + } else if (configRegistry.resourceExists(DEFAULT_TEMPLATE)){ + template = configRegistry.get(DEFAULT_TEMPLATE); + } + if (template != null) { + Object object = template.getContent(); + if (object != null) { + String content; + if (object instanceof String){ + content = (String)object; + }else { + content = new String((byte[])object); + } + return content.replace("$$message$$", message); + } + } + } catch (RegistryException e) { + log.warn("An error occurred while accessing email template from the registry"); + } + + return null; + } +} diff --git a/components/registry/org.wso2.carbon.registry.info.ui/src/main/resources/org/wso2/carbon/registry/info/ui/i18n/Resources.properties b/components/registry/org.wso2.carbon.registry.info.ui/src/main/resources/org/wso2/carbon/registry/info/ui/i18n/Resources.properties index 7798d774c..abea0e0a4 100644 --- a/components/registry/org.wso2.carbon.registry.info.ui/src/main/resources/org/wso2/carbon/registry/info/ui/i18n/Resources.properties +++ b/components/registry/org.wso2.carbon.registry.info.ui/src/main/resources/org/wso2/carbon/registry/info/ui/i18n/Resources.properties @@ -89,3 +89,10 @@ digest.monthly=Monthly page.x.to.y=Page {0} prev=Prev next=Next + +publisher.checklist.checked=Publisher Checklist Check +publisher.checklist.unchecked=Publisher Checklist Uncheck +publisher.lifecycle.state.changed=Publisher Lifecycle Change +publisher.update=Publisher Update +store.lifecycle.state.changed=Store Lifecycle Change +store.update=Store Update diff --git a/components/registry/org.wso2.carbon.registry.info.ui/src/main/resources/web/info/subscription-ajaxprocessor.jsp b/components/registry/org.wso2.carbon.registry.info.ui/src/main/resources/web/info/subscription-ajaxprocessor.jsp index 91b9001d6..bd5ad9b5e 100644 --- a/components/registry/org.wso2.carbon.registry.info.ui/src/main/resources/web/info/subscription-ajaxprocessor.jsp +++ b/components/registry/org.wso2.carbon.registry.info.ui/src/main/resources/web/info/subscription-ajaxprocessor.jsp @@ -44,6 +44,7 @@ String[] events = null; String[] resourceEventNames = null; String[] collectionEventNames = null; + boolean[] isEventVisible = null; SubscriptionInstance[] subscriptions = null; boolean isResource = true; boolean canUnsubscribe = false; @@ -107,11 +108,17 @@ events = new String[eventTypes.length]; resourceEventNames = new String[eventTypes.length]; collectionEventNames = new String[eventTypes.length]; + isEventVisible = new boolean[eventTypes.length]; for (int i = 0; i < eventTypes.length; i++) { if (eventTypes[i] != null) { events[i] = eventTypes[i].getId(); resourceEventNames[i] = eventTypes[i].getResourceEvent(); collectionEventNames[i] = eventTypes[i].getCollectionEvent(); + if (eventTypes[i].getId().startsWith("publisher") || eventTypes[i].getId().startsWith("store")){ + isEventVisible[i] = false; + } else{ + isEventVisible[i] = true; + } } } isResource = client.isResource(request); @@ -170,7 +177,7 @@ <% for (int i = 0; i < events.length; i++) { if (isResource) { - if (resourceEventNames[i] != null) { + if (resourceEventNames[i] != null && isEventVisible[i]) { %> <% } - } else if (collectionEventNames[i] != null) { + } else if (collectionEventNames[i] != null && isEventVisible[i]) { %>