revert-70aa11f8
prabathabey 9 years ago
commit 5e03c5ed30

@ -157,6 +157,16 @@
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId> <artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

@ -59,6 +59,7 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
} }
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName(); .getRealmConfiguration().getAdminUserName();
username = username + "@" + APIUtil.getTenantDomainOftheUser();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
@ -81,7 +82,7 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
@POST @POST
public Response register(RegistrationProfile registrationProfile) { public Response register(RegistrationProfile registrationProfile) {
try { try {
String username = APIUtil.getAuthenticatedUser(); String username = APIUtil.getAuthenticatedUser() + "@" + APIUtil.getTenantDomainOftheUser();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
if (registrationProfile.isMappingAnExistingOAuthApp()) { if (registrationProfile.isMappingAnExistingOAuthApp()) {
JSONObject jsonStringObject = new JSONObject(); JSONObject jsonStringObject = new JSONObject();
@ -116,7 +117,7 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
@DELETE @DELETE
public Response unregister(@QueryParam("applicationName") String applicationName) { public Response unregister(@QueryParam("applicationName") String applicationName) {
try { try {
String username = APIUtil.getAuthenticatedUser(); String username = APIUtil.getAuthenticatedUser() + "@" + APIUtil.getTenantDomainOftheUser();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
apiManagementProviderService.removeAPIApplication(applicationName, username); apiManagementProviderService.removeAPIApplication(applicationName, username);
return Response.status(Response.Status.ACCEPTED).build(); return Response.status(Response.Status.ACCEPTED).build();

@ -0,0 +1,118 @@
package org.wso2.carbon.apimgt.application.extension.api.filter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.application.extension.api.util.APIUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* this filter check for permission for the request
*/
public class ApiPermissionFilter implements Filter{
private static final Log log = LogFactory.getLog(ApiPermissionFilter.class);
private static final String UI_EXECUTE = "ui.execute";
private static final String PERMISSION_CONFIG_PATH = File.separator + "META-INF" + File.separator
+ "permissions.xml";
private static final String PERMISSION_PREFIX = "/permission/admin";
private static List<Permission> permissions;
private static final String WEBAPP_CONTEXT = "/api-application-registration";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
InputStream permissionStream = filterConfig.getServletContext().getResourceAsStream(PERMISSION_CONFIG_PATH);
if (permissionStream != null) {
try {
JAXBContext cdmContext = JAXBContext.newInstance(PermissionConfiguration.class);
Unmarshaller unmarshaller = cdmContext.createUnmarshaller();
PermissionConfiguration permissionConfiguration = (PermissionConfiguration)
unmarshaller.unmarshal(permissionStream);
permissions = permissionConfiguration.getPermissions();
} catch (JAXBException e) {
log.error("invalid permissions.xml", e);
}
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
if (servletRequest instanceof HttpServletRequest) {
String uri = ((HttpServletRequest)servletRequest).getRequestURI();
boolean status = false;
if (uri.contains("register/tenants")) {
String urlPermission = getPermission("/register/tenants/*");
if (urlPermission != null) {
status = isUserAuthorized(PERMISSION_PREFIX + urlPermission, UI_EXECUTE);
}
} else {
String urlPermission = getPermission(uri);
if (urlPermission != null) {
status = isUserAuthorized(PERMISSION_PREFIX + urlPermission, UI_EXECUTE);
}
}
if (status) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
HttpServletResponse res = (HttpServletResponse) servletResponse;
res.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
} else {
HttpServletResponse res = (HttpServletResponse) servletResponse;
res.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
@Override
public void destroy() {
//do nothing
}
private static String getPermission(String url) {
if (permissions != null) {
for (int i = 0; i < permissions.size(); i++) {
Permission permission = permissions.get(i);
if ((WEBAPP_CONTEXT + permission.getUrl()).equals(url)) {
return permission.getPath();
}
}
}
return null;
}
/**
* Check whether the client is authorized with the given permission and action.
* @param permission Carbon permission that requires for the use
* @param action Carbon permission action that requires for the given permission.
* @return boolean - true if user is authorized else return false.
*/
private boolean isUserAuthorized(String permission, String action) {
PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = context.getUsername();
try {
UserRealm userRealm = APIUtil.getRealmService().getTenantUserRealm(PrivilegedCarbonContext
.getThreadLocalCarbonContext().getTenantId());
return userRealm.getAuthorizationManager().isUserAuthorized(username, permission, action);
} catch (UserStoreException e) {
String errorMsg = String.format("Unable to authorize the user : %s", username, e);
log.error(errorMsg, e);
return false;
}
}
}

@ -0,0 +1,60 @@
/*
* 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.apimgt.application.extension.api.filter;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* This class represents the information related to permission.
*/
@XmlRootElement (name = "Permission")
public class Permission {
private String path; // permission string
private String url; // url of the resource
private String method; // http method
public String getPath() {
return path;
}
@XmlElement (name = "path", required = true)
public void setPath(String path) {
this.path = path;
}
public String getUrl() {
return url;
}
@XmlElement (name = "url", required = true)
public void setUrl(String url) {
this.url = url;
}
public String getMethod() {
return method;
}
@XmlElement (name = "method", required = true)
public void setMethod(String method) {
this.method = method;
}
}

@ -0,0 +1,41 @@
/*
* 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.apimgt.application.extension.api.filter;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
/**
* This class represents the information related to permission configuration.
*/
@XmlRootElement (name = "PermissionConfiguration")
public class PermissionConfiguration {
private List<Permission> permissions;
public List<Permission> getPermissions() {
return permissions;
}
@XmlElement (name = "Permission", required = true)
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
}
}

@ -22,6 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.user.core.service.RealmService;
/** /**
* This class provides utility functions used by REST-API. * This class provides utility functions used by REST-API.
@ -57,4 +58,16 @@ public class APIUtil {
} }
return apiManagementProviderService; return apiManagementProviderService;
} }
public static RealmService getRealmService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService =
(RealmService) ctx.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "Device Management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return realmService;
}
} }

@ -30,21 +30,21 @@
<!-- Device related APIs --> <!-- Device related APIs -->
<Permission> <Permission>
<name>Register tenant specific application</name> <name>Register tenant specific application</name>
<path>/device-mgt</path> <path>/device-mgt/admin</path>
<url>/register/tenants/*</url> <url>/register/tenants/*</url>
<method>POST</method> <method>POST</method>
<scope>super_admin_user</scope> <scope>super_admin_user</scope>
</Permission> </Permission>
<Permission> <Permission>
<name>Register application</name> <name>Register application</name>
<path>/device-mgt/api/application/add</path> <path>/device-mgt/user/api/application</path>
<url>/register</url> <url>/register</url>
<method>POST</method> <method>POST</method>
<scope>application_user</scope> <scope>application_user</scope>
</Permission> </Permission>
<Permission> <Permission>
<name>Delete application</name> <name>Delete application</name>
<path>/device-mgt/api/application/remove</path> <path>/device-mgt/user/api/application</path>
<url>/unregister</url> <url>/unregister</url>
<method>DELETE</method> <method>DELETE</method>
<scope>application_user</scope> <scope>application_user</scope>

@ -49,4 +49,14 @@
<param-name>managed-api-enabled</param-name> <param-name>managed-api-enabled</param-name>
<param-value>false</param-value> <param-value>false</param-value>
</context-param> </context-param>
<filter>
<filter-name>ApiPermissionFilter</filter-name>
<filter-class>org.wso2.carbon.apimgt.application.extension.api.filter.ApiPermissionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiPermissionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app> </web-app>

@ -29,6 +29,6 @@ var utility = require("/app/modules/utility.js")["utility"];
var permissions = { var permissions = {
'/permission/admin/device-mgt/user': ['ui.execute'], '/permission/admin/device-mgt/user': ['ui.execute'],
'/permission/admin/device-mgt/api/application': ['ui.execute'] '/permission/admin/manage/api/subscribe': ['ui.execute']
}; };
userModule.addRole("internal/devicemgt-user", ["admin"], permissions); userModule.addRole("internal/devicemgt-user", ["admin"], permissions);

@ -27,7 +27,7 @@ import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.registry.api.Registry; import org.wso2.carbon.registry.api.Registry;
import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.RegistryException;
import java.io.*; import java.io.InputStream;
public class RegistryBasedResourceLoader extends ResourceLoader { public class RegistryBasedResourceLoader extends ResourceLoader {
@ -46,12 +46,12 @@ public class RegistryBasedResourceLoader extends ResourceLoader {
if (registry == null) { if (registry == null) {
throw new IllegalStateException("No valid registry instance is attached to the current carbon context"); throw new IllegalStateException("No valid registry instance is attached to the current carbon context");
} }
if (!registry.resourceExists(EMAIL_CONFIG_BASE_LOCATION + "/" + name + ".vm")) { if (!registry.resourceExists(EMAIL_CONFIG_BASE_LOCATION + "/" + name)) {
throw new ResourceNotFoundException("Resource '" + name + "' does not exist"); throw new ResourceNotFoundException("Resource '" + name + "' does not exist");
} }
org.wso2.carbon.registry.api.Resource resource = org.wso2.carbon.registry.api.Resource resource =
registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name + ".vm"); registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name);
resource.setMediaType("text/plain");
return resource.getContentStream(); return resource.getContentStream();
} catch (RegistryException e) { } catch (RegistryException e) {
throw new ResourceNotFoundException("Error occurred while retrieving resource", e); throw new ResourceNotFoundException("Error occurred while retrieving resource", e);

@ -21,22 +21,11 @@ package org.wso2.carbon.email.sender.core.internal;
import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.email.sender.core.EmailSenderConfigurationFailedException; import org.wso2.carbon.email.sender.core.EmailSenderConfigurationFailedException;
import org.wso2.carbon.registry.api.Collection;
import org.wso2.carbon.registry.api.Registry;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File; class EmailSenderAxis2ConfigContextObserver implements Axis2ConfigurationContextObserver {
import java.io.FilenameFilter;
public class EmailSenderAxis2ConfigContextObserver implements Axis2ConfigurationContextObserver {
private static final String EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH = "email-templates";
private static final Log log = LogFactory.getLog(EmailSenderAxis2ConfigContextObserver.class); private static final Log log = LogFactory.getLog(EmailSenderAxis2ConfigContextObserver.class);
@Override @Override
@ -47,7 +36,7 @@ public class EmailSenderAxis2ConfigContextObserver implements Axis2Configuration
@Override @Override
public void createdConfigurationContext(ConfigurationContext configurationContext) { public void createdConfigurationContext(ConfigurationContext configurationContext) {
try { try {
this.setupEmailTemplates(); EmailUtils.setupEmailTemplates();
} catch (EmailSenderConfigurationFailedException e) { } catch (EmailSenderConfigurationFailedException e) {
log.error("Error occurred while setting up email templates", e); log.error("Error occurred while setting up email templates", e);
} }
@ -63,50 +52,4 @@ public class EmailSenderAxis2ConfigContextObserver implements Axis2Configuration
} }
private void setupEmailTemplates() throws EmailSenderConfigurationFailedException {
File templateDir =
new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources"
+ File.separator + "email-templates");
if (!templateDir.exists()) {
if (log.isDebugEnabled()) {
log.debug("The directory that is expected to use as the container for all email templates is not " +
"available. Therefore, no template is uploaded to the registry");
}
}
if (templateDir.canRead()) {
File[] templates = templateDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
name = name.toLowerCase();
return name.endsWith(".vm");
}
});
try {
Registry registry =
CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);
if (!registry.resourceExists(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH)) {
Collection collection = registry.newCollection();
registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH, collection);
for (File template : templates) {
Resource resource = registry.newResource();
resource.setContent(template);
registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + template.getName(), resource);
}
} else {
for (File template : templates) {
if (!registry.resourceExists(
EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + template.getName())) {
Resource resource = registry.newResource();
resource.setContent(template);
registry.put(
EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + template.getName(), resource);
}
}
}
} catch (RegistryException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while setting up email templates", e);
}
}
}
} }

@ -17,28 +17,16 @@
*/ */
package org.wso2.carbon.email.sender.core.internal; package org.wso2.carbon.email.sender.core.internal;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.email.sender.core.EmailSenderConfig; import org.wso2.carbon.email.sender.core.EmailSenderConfig;
import org.wso2.carbon.email.sender.core.EmailSenderConfigurationFailedException;
import org.wso2.carbon.email.sender.core.service.EmailSenderService; import org.wso2.carbon.email.sender.core.service.EmailSenderService;
import org.wso2.carbon.email.sender.core.service.EmailSenderServiceImpl; import org.wso2.carbon.email.sender.core.service.EmailSenderServiceImpl;
import org.wso2.carbon.registry.api.Collection;
import org.wso2.carbon.registry.api.Registry;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
/** /**
* @scr.component name="org.wso2.carbon.email.sender.EmailSenderServiceComponent" immediate="true" * @scr.component name="org.wso2.carbon.email.sender.EmailSenderServiceComponent" immediate="true"
* @scr.reference name="registry.service" * @scr.reference name="registry.service"
@ -56,7 +44,6 @@ import java.io.IOException;
*/ */
public class EmailSenderServiceComponent { public class EmailSenderServiceComponent {
private static final String EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH = "/email-templates";
private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class); private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class);
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -69,7 +56,7 @@ public class EmailSenderServiceComponent {
EmailSenderConfig.init(); EmailSenderConfig.init();
/* Setting up default email templates */ /* Setting up default email templates */
this.setupEmailTemplates(); EmailUtils.setupEmailTemplates();
/* Registering declarative service instances exposed by EmailSenderServiceComponent */ /* Registering declarative service instances exposed by EmailSenderServiceComponent */
this.registerServices(componentContext); this.registerServices(componentContext);
@ -98,64 +85,6 @@ public class EmailSenderServiceComponent {
componentContext.getBundleContext().registerService(EmailSenderService.class, emailServiceProvider, null); componentContext.getBundleContext().registerService(EmailSenderService.class, emailServiceProvider, null);
} }
private void setupEmailTemplates() throws EmailSenderConfigurationFailedException {
File templateDir =
new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator +
"resources" + File.separator + "email-templates");
if (!templateDir.exists()) {
if (log.isDebugEnabled()) {
log.debug("The directory that is expected to use as the container for all email templates is not " +
"available. Therefore, no template is uploaded to the registry");
}
}
if (templateDir.canRead()) {
File[] templates = templateDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
name = name.toLowerCase();
return name.endsWith(".vm");
}
});
try {
Registry registry =
EmailSenderDataHolder.getInstance().getRegistryService().getConfigSystemRegistry();
if (!registry.resourceExists(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH)) {
Collection collection = registry.newCollection();
registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH, collection);
for (File template : templates) {
Resource resource = registry.newResource();
String contents = FileUtils.readFileToString(template);
resource.setContent(contents.getBytes());
registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + template.getName(), resource);
}
} else {
/* Existence of a given resource is not checked consciously, before performing registry.put() below.
* The rationale is that, the only less expensive way that one can check if a resource exists is
* that through registry.resourceExists(), which only checks if 'some' resource exists at the given
* registry path. However, this does not capture scenarios where there can be updated contents to
* the same resource of which the path hasn't changed after it has been initialized for the first
* time. Therefore, whenever the server starts-up, all email templates are updated just to avoid
* the aforementioned problem */
for (File template : templates) {
Resource resource = registry.newResource();
String contents = FileUtils.readFileToString(template);
resource.setContent(contents.getBytes());
registry.put(
EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + template.getName(), resource);
}
}
} catch (RegistryException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while setting up email templates", e);
} catch (FileNotFoundException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while writing template file " +
"contents as an input stream of a resource", e);
} catch (IOException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while serializing file " +
"contents to a string", e);
}
}
}
/** /**
* Sets Registry Service. * Sets Registry Service.
* *

@ -0,0 +1,87 @@
/*
* Copyright (c) 2014, 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.email.sender.core.internal;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.email.sender.core.EmailSenderConfigurationFailedException;
import org.wso2.carbon.registry.api.Collection;
import org.wso2.carbon.registry.api.Registry;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
class EmailUtils {
private static final String EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH = "/email-templates";
private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class);
static void setupEmailTemplates() throws EmailSenderConfigurationFailedException {
File templateDir =
new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator +
"resources" + File.separator + "email-templates");
if (!templateDir.exists()) {
if (log.isDebugEnabled()) {
log.debug("The directory that is expected to use as the container for all email templates is not " +
"available. Therefore, no template is uploaded to the registry");
}
}
if (templateDir.canRead()) {
File[] templates = templateDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
name = name.toLowerCase();
return name.endsWith(".vm");
}
});
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
Registry registry =
EmailSenderDataHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
if (!registry.resourceExists(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH)) {
Collection collection = registry.newCollection();
registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH, collection);
for (File template : templates) {
Resource resource = registry.newResource();
resource.setMediaType("text/plain");
String contents = FileUtils.readFileToString(template);
resource.setContent(contents);
registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/"
+ template.getName().replace(".vm", ""), resource);
}
}
} catch (RegistryException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while setting up email templates", e);
} catch (FileNotFoundException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while writing template file " +
"contents as an input stream of a resource", e);
} catch (IOException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while serializing file " +
"contents to a string", e);
}
}
}
}
Loading…
Cancel
Save