You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by pr...@apache.org on 2014/04/17 04:43:29 UTC
[49/52] [partial] forking carbon ui bundle in to stratos code base
and removing license incompatible JS and packing the new module to carbon
runtime, through dropins
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6b1dba58/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUILoginUtil.java
----------------------------------------------------------------------
diff --git a/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUILoginUtil.java b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUILoginUtil.java
new file mode 100644
index 0000000..ba05a7b
--- /dev/null
+++ b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUILoginUtil.java
@@ -0,0 +1,596 @@
+/*
+ * Copyright (c) 2005-2010, 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.ui;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.core.common.AuthenticationException;
+import org.wso2.carbon.ui.tracker.AuthenticatorRegistry;
+import org.wso2.carbon.utils.UserUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.IOException;
+import java.util.regex.Pattern;
+
+public final class CarbonUILoginUtil {
+
+ private static Log log = LogFactory.getLog(CarbonUILoginUtil.class);
+ private static Pattern tenantEnabledUriPattern;
+ private static final String TENANT_ENABLED_URI_PATTERN = "(/.*/|/)"
+ + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/[^/]*($|/.*)";
+ protected static final int RETURN_FALSE = 0;
+ protected static final int RETURN_TRUE = 1;
+ protected static final int CONTINUE = 2;
+
+ static {
+ tenantEnabledUriPattern = Pattern.compile(TENANT_ENABLED_URI_PATTERN);
+ }
+
+ /**
+ *
+ * @return
+ */
+ protected static Pattern getTenantEnabledUriPattern() {
+ return tenantEnabledUriPattern;
+ }
+
+ /**
+ * Returns the corresponding CarbonAuthenticator based on the request.
+ *
+ * @param request
+ * @return
+ */
+ protected static CarbonUIAuthenticator getAuthenticator(HttpServletRequest request) {
+ return AuthenticatorRegistry.getCarbonAuthenticator(request);
+ }
+
+ /**
+ *
+ * @param authenticator
+ * @param request
+ * @param response
+ * @param session
+ * @param skipLoginPage
+ * @param contextPath
+ * @param indexPageURL
+ * @param requestedURI
+ * @return
+ * @throws IOException
+ */
+ protected static boolean saveOriginalUrl(CarbonUIAuthenticator authenticator,
+ HttpServletRequest request, HttpServletResponse response, HttpSession session,
+ boolean skipLoginPage, String contextPath, String indexPageURL, String requestedURI)
+ throws IOException {
+
+ // Saving originally requested url should not forward to error page after login
+ if (!requestedURI.endsWith("admin/error.jsp")) {
+ String queryString = request.getQueryString();
+ String tmpURI;
+ if (queryString != null) {
+ tmpURI = requestedURI + "?" + queryString;
+ } else {
+ tmpURI = requestedURI;
+ }
+ tmpURI = "../.." + tmpURI;
+ request.getSession(false).setAttribute("requestedUri", tmpURI);
+ if (!tmpURI.contains("session-validate.jsp") && !("/null").equals(requestedURI)) {
+ // Also setting it in a cookie, for non-remember-me cases
+ Cookie cookie = new Cookie("requestedURI", tmpURI);
+ cookie.setPath("/");
+ response.addCookie(cookie);
+ }
+ }
+
+ try {
+ Cookie[] cookies = request.getCookies();
+ if (cookies != null) {
+ for (Cookie cookie : cookies) {
+ if (cookie.getName().equals(CarbonConstants.REMEMBER_ME_COOKE_NAME)
+ && authenticator != null) {
+ try {
+ authenticator.authenticateWithCookie(request);
+ return true;
+ } catch (AuthenticationException ignored) {
+ // We can ignore here and proceed with normal login.
+ if (log.isDebugEnabled()) {
+ log.debug(ignored);
+ }
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ log.error("error occurred while login", e);
+ }
+
+ if (request.getAttribute(MultitenantConstants.TENANT_DOMAIN) != null) {
+ if (skipLoginPage) {
+ response.sendRedirect("../admin/login_action.jsp");
+ } else {
+ response.sendRedirect("../admin/login.jsp");
+ }
+ } else {
+ if (skipLoginPage) {
+ response.sendRedirect(contextPath + "/carbon/admin/login_action.jsp");
+ } else {
+ response.sendRedirect(contextPath + "/carbon/admin/login.jsp");
+
+ }
+ }
+ return false;
+ }
+
+ /**
+ *
+ * @param request
+ * @param indexPageURL
+ * @return
+ */
+ protected static String getCustomIndexPage(HttpServletRequest request, String indexPageURL) {
+ // If a custom index page is used send the login request with the index page specified
+ if (request.getParameter(CarbonConstants.INDEX_PAGE_URL) != null) {
+ return request.getParameter(CarbonConstants.INDEX_PAGE_URL);
+ } else if (indexPageURL == null) {
+ return "/carbon/admin/index.jsp";
+ }
+
+ return indexPageURL;
+ }
+
+ /**
+ *
+ * @param requestedURI
+ * @param indexPageURL
+ * @param request
+ * @return
+ */
+ protected static String getIndexPageUrlFromCookie(String requestedURI, String indexPageURL,
+ HttpServletRequest request) {
+ if (requestedURI.equals("/carbon/admin/login_action.jsp")) {
+ Cookie[] cookies = request.getCookies();
+ if (cookies != null) {
+ for (Cookie cookie : cookies) {
+ if (cookie.getName().equals("requestedURI")) {
+ indexPageURL = cookie.getValue();
+ }
+ }
+ // Removing any tenant specific strings from the cookie value for the indexPageURL
+ if (tenantEnabledUriPattern.matcher(indexPageURL).matches()) {
+ indexPageURL = CarbonUIUtil.removeTenantSpecificStringsFromURL(indexPageURL);
+ }
+ }
+ }
+ return indexPageURL;
+ }
+
+ /**
+ *
+ * @param requestedURI
+ * @return
+ */
+ protected static boolean letRequestedUrlIn(String requestedURI, String tempUrl) {
+ if (requestedURI.endsWith(".css") || requestedURI.endsWith(".gif")
+ || requestedURI.endsWith(".GIF") || requestedURI.endsWith(".jpg")
+ || requestedURI.endsWith(".JPG") || requestedURI.endsWith(".png")
+ || requestedURI.endsWith(".PNG") || requestedURI.endsWith(".xsl")
+ || requestedURI.endsWith(".xslt") || requestedURI.endsWith(".js")
+ || requestedURI.startsWith("/registry") || requestedURI.endsWith(".html")
+ || requestedURI.endsWith(".ico") || requestedURI.startsWith("/openid/")
+ || requestedURI.indexOf("/openid/") > -1
+ || requestedURI.indexOf("/openidserver") > -1
+ || requestedURI.indexOf("/gadgets") > -1 || requestedURI.indexOf("/samlsso") > -1) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ *
+ * @param authenticator
+ * @param request
+ * @param response
+ * @param session
+ * @param authenticated
+ * @param contextPath
+ * @param indexPageURL
+ * @param httpLogin
+ * @return
+ * @throws IOException
+ */
+ protected static boolean handleLogout(CarbonUIAuthenticator authenticator,
+ HttpServletRequest request, HttpServletResponse response, HttpSession session,
+ boolean authenticated, String contextPath, String indexPageURL, String httpLogin)
+ throws IOException {
+ log.debug("Handling Logout..");
+ // Logout the user from the back-end
+ try {
+ authenticator = (CarbonUIAuthenticator) session
+ .getAttribute(CarbonSecuredHttpContext.CARBON_AUTHNETICATOR);
+ if (authenticator != null) {
+ authenticator.unauthenticate(request);
+ log.debug("Backend session invalidated");
+ }
+ } catch (Exception e) {
+ log.error(e.getMessage(), e);
+ response.sendRedirect("../admin/login.jsp");
+ return false;
+ }
+
+ // Only applicable if this is SAML2 based SSO. Complete the logout action after receiving
+ // the Logout response.
+ if ("true".equals(request.getParameter("logoutcomplete"))) {
+ HttpSession currentSession = request.getSession(false);
+ if (currentSession != null) {
+ // check if current session has expired
+ session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
+ session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
+ try {
+ session.invalidate();
+ } catch (Exception ignored) { // Ignore exception when
+ // invalidating and
+ // invalidated session
+ }
+ log.debug("Frontend session invalidated");
+ }
+ response.sendRedirect("../../carbon/admin/login.jsp");
+ return false;
+ }
+
+ if (request.getAttribute("ExternalLogoutPage") != null) {
+ HttpSession currentSession = request.getSession(false);
+ if (currentSession != null) {
+ session.removeAttribute("logged-user");
+ session.getServletContext().removeAttribute("logged-user");
+ try {
+ session.invalidate();
+ } catch (Exception ignored) {
+ }
+ log.debug("Frontend session invalidated");
+ }
+
+ response.sendRedirect((String) request.getAttribute("ExternalLogoutPage"));
+ return false;
+ }
+
+ CarbonSSOSessionManager ssoSessionManager = CarbonSSOSessionManager.getInstance();
+
+ if (!ssoSessionManager.skipSSOSessionInvalidation(request, authenticator)
+ && !ssoSessionManager.isSessionValid(request.getSession().getId())) {
+ HttpSession currentSession = request.getSession(false);
+ if (currentSession != null) {
+ // check if current session has expired
+ session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
+ session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
+ try {
+ session.invalidate();
+ log.debug("SSO session session invalidated ");
+ } catch (Exception ignored) { // Ignore exception when
+ // Invalidating and invalidated session
+ if (log.isDebugEnabled()) {
+ log.debug("Ignore exception when invalidating session", ignored);
+ }
+ }
+ }
+ response.sendRedirect("../.." + indexPageURL);
+ return false;
+ }
+
+ // Memory clean up : remove invalid session from the invalid session list.
+ ssoSessionManager.removeInvalidSession(request.getSession().getId());
+
+ // This condition is evaluated when users are logged out in SAML2 based SSO
+ if (request.getAttribute("logoutRequest") != null) {
+ log.debug("Loging out from SSO session");
+ response.sendRedirect("../../carbon/sso-acs/redirect_ajaxprocessor.jsp?logout=true");
+ return false;
+ }
+
+ HttpSession currentSession = request.getSession(false);
+ if (currentSession != null) {
+ // Check if current session has expired
+ session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
+ session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
+ try {
+ session.invalidate();
+ log.debug("Frontend session invalidated");
+ } catch (Exception ignored) {
+ // Ignore exception when invalidating and invalidated session
+ }
+ }
+
+ Cookie rmeCookie = new Cookie(CarbonConstants.REMEMBER_ME_COOKE_NAME, null);
+ rmeCookie.setPath("/");
+ rmeCookie.setSecure(true);
+ rmeCookie.setMaxAge(0);
+ response.addCookie(rmeCookie);
+ response.sendRedirect(contextPath + indexPageURL);
+ return false;
+ }
+
+ /**
+ *
+ * @param authenticator
+ * @param request
+ * @param response
+ * @param session
+ * @param authenticated
+ * @param contextPath
+ * @param indexPageURL
+ * @param httpLogin
+ * @return
+ * @throws IOException
+ */
+ protected static boolean handleLogin(CarbonUIAuthenticator authenticator,
+ HttpServletRequest request, HttpServletResponse response, HttpSession session,
+ boolean authenticated, String contextPath, String indexPageURL, String httpLogin)
+ throws IOException {
+ try {
+
+ // commenting out this method as it is not required
+// String[] username = (String[])request.getParameterMap().get(AbstractCarbonUIAuthenticator.USERNAME);
+// if(username != null && !username[0].contains("/") && UserUtils.hasMultipleUserStores()){
+// response.sendRedirect("../../carbon/admin/login.jsp?loginStatus=false&errorCode=domain.not.specified");
+// return false;
+// }
+
+ authenticator.authenticate(request);
+ session = request.getSession();
+ session.setAttribute(CarbonSecuredHttpContext.CARBON_AUTHNETICATOR, authenticator);
+
+ // Check if the username is of type bob@acme.com if so, this is a login from a
+ // multi-tenant deployment
+ // The tenant id part(i.e. acme.com) should be set into http session for further UI
+ // related processing
+ String userName = (String) request.getAttribute(AbstractCarbonUIAuthenticator.USERNAME);
+
+ if(log.isDebugEnabled()) {
+ log.debug("Login request from " + userName);
+ }
+ String tenantDomain = null;
+ if (request.getAttribute(MultitenantConstants.TENANT_DOMAIN) != null) {
+ tenantDomain = (String) request.getAttribute(MultitenantConstants.TENANT_DOMAIN);
+
+ }
+ if (tenantDomain == null) {
+ tenantDomain = MultitenantUtils.getTenantDomain(userName);
+ }
+ if (tenantDomain != null
+ && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
+ // we will add it to the context
+ contextPath += "/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/"
+ + tenantDomain;
+ }
+
+ String value = request.getParameter("rememberMe");
+ boolean isRememberMe = false;
+ if (value != null && value.equals("rememberMe")) {
+ isRememberMe = true;
+ }
+
+ try {
+ if (isRememberMe) {
+ String rememberMeCookieValue = (String) request
+ .getAttribute(CarbonConstants.REMEMBER_ME_COOKIE_VALUE);
+ int age = Integer.parseInt((String) request
+ .getAttribute(CarbonConstants.REMEMBER_ME_COOKIE_AGE));
+
+ Cookie rmeCookie = new Cookie(CarbonConstants.REMEMBER_ME_COOKE_NAME,
+ rememberMeCookieValue);
+ rmeCookie.setPath("/");
+ rmeCookie.setSecure(true);
+ rmeCookie.setMaxAge(age);
+ response.addCookie(rmeCookie);
+ }
+ } catch (Exception e) {
+ response.sendRedirect(contextPath + indexPageURL
+ + (indexPageURL.indexOf('?') == -1 ? "?" : "&") + "loginStatus=false");
+ if (log.isDebugEnabled()) {
+ log.debug("Security check failed for login request for " + userName);
+ }
+ return false;
+ }
+ if (contextPath != null) {
+ if (indexPageURL.startsWith("../..")) {
+ indexPageURL = indexPageURL.substring(5);
+ }
+
+ response.sendRedirect(contextPath + indexPageURL
+ + (indexPageURL.indexOf('?') == -1 ? "?" : "&") + "loginStatus=true");
+ }
+
+ } catch (AuthenticationException e) {
+ log.debug("Authentication failure ...", e);
+ try {
+ request.getSession().invalidate();
+ getAuthenticator(request).unauthenticate(request);
+ if (httpLogin != null) {
+ response.sendRedirect(httpLogin + "?loginStatus=false");
+ return false;
+ } else {
+ response.sendRedirect("/carbon/admin/login.jsp?loginStatus=false");
+ return false;
+ }
+ } catch (Exception e1) {
+ // ignore exception
+ }
+
+ } catch (Exception e) {
+ log.error("error occurred while login", e);
+ response.sendRedirect("../../carbon/admin/login.jsp?loginStatus=failed");
+ }
+
+ return false;
+ }
+
+ /**
+ *
+ * @param requestedURI
+ * @param request
+ * @return
+ */
+ protected static String getForcedSignOutRequestedURI(String requestedURI,
+ HttpServletRequest request) {
+ if (requestedURI.endsWith(".jsp")
+ && !requestedURI.endsWith("ajaxprocessor.jsp")
+ && !requestedURI.endsWith("session_validate.jsp")
+ && (request.getSession().getAttribute("authenticated")) != null
+ && ((Boolean) (request.getSession().getAttribute("authenticated"))).booleanValue()
+ && ((request.getSession().getAttribute(MultitenantConstants.TENANT_DOMAIN) == null && request
+ .getAttribute(MultitenantConstants.TENANT_DOMAIN) != null) || ((request
+ .getSession().getAttribute(MultitenantConstants.TENANT_DOMAIN) != null && request
+ .getAttribute(MultitenantConstants.TENANT_DOMAIN) != null) && !request
+ .getSession().getAttribute(MultitenantConstants.TENANT_DOMAIN)
+ .equals(request.getAttribute(MultitenantConstants.TENANT_DOMAIN))))) {
+ // If someone signed in from a tenant, try to access a different tenant domain, he
+ // should be forced to sign out without any prompt Cloud requirement
+ requestedURI = "../admin/logout_action.jsp";
+ }
+
+ return requestedURI;
+ }
+
+ /**
+ *
+ * @param requestedURI
+ * @param request
+ * @param response
+ * @param authenticated
+ * @param context
+ * @param indexPageURL
+ * @return
+ * @throws IOException
+ */
+ protected static int handleLoginPageRequest(String requestedURI, HttpServletRequest request,
+ HttpServletResponse response, boolean authenticated, String context, String indexPageURL)
+ throws IOException {
+ if (requestedURI.indexOf("login.jsp") > -1
+ || requestedURI.indexOf("login_ajaxprocessor.jsp") > -1
+ || requestedURI.indexOf("admin/layout/template.jsp") > -1
+ || requestedURI.endsWith("/filedownload") || requestedURI.endsWith("/fileupload")
+ || requestedURI.indexOf("/fileupload/") > -1
+ || requestedURI.indexOf("login_action.jsp") > -1
+ || requestedURI.indexOf("admin/jsp/WSRequestXSSproxy_ajaxprocessor.jsp") > -1) {
+
+ if ((requestedURI.indexOf("login.jsp") > -1
+ || requestedURI.indexOf("login_ajaxprocessor.jsp") > -1 || requestedURI
+ .indexOf("login_action.jsp") > -1) && authenticated) {
+ // User has typed the login page url, while being logged in
+ if (request.getSession().getAttribute(MultitenantConstants.TENANT_DOMAIN) != null) {
+ String tenantDomain = (String) request.getSession().getAttribute(
+ MultitenantConstants.TENANT_DOMAIN);
+ if (tenantDomain != null
+ && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
+ context += "/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/"
+ + tenantDomain;
+ }
+ }
+ if(log.isDebugEnabled()){
+ log.debug("User already authenticated. Redirecting to " + indexPageURL);
+ }
+ // redirect relative to the servlet container root
+ response.sendRedirect(context + "/carbon/admin/index.jsp");
+ return RETURN_FALSE;
+ } else if (requestedURI.indexOf("login_action.jsp") > -1 && !authenticated) {
+ // User is not yet authenticated and now trying to get authenticated
+ // do nothing, leave for authentication at the end
+ if (log.isDebugEnabled()) {
+ log.debug("User is not yet authenticated and now trying to get authenticated;"
+ + "do nothing, leave for authentication at the end");
+ }
+ return CONTINUE;
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Skipping security checks for " + requestedURI);
+ }
+ return RETURN_TRUE;
+ }
+ }
+
+ return CONTINUE;
+ }
+
+ /**
+ *
+ * @param authenticated
+ * @param response
+ * @param requestedURI
+ * @param context
+ * @return
+ * @throws IOException
+ */
+ protected static boolean escapeTenantWebAppRequests(boolean authenticated,
+ HttpServletResponse response, String requestedURI, String context) throws IOException {
+ // Tenant webapp requests should never reach Carbon. It can happen
+ // if Carbon is deployed at / context and requests for non-existent tenant webapps is made.
+ if (requestedURI.contains("/webapps/")) {
+ response.sendError(404, "Web application not found. Request URI: " + requestedURI);
+ return false;
+ } else if (requestedURI.contains("/carbon/admin/login.jsp") && !authenticated) {
+ // a tenant requesting login.jsp while not being authenticated
+ // redirecting the tenant login page request to the root /carbon/admin/login.jsp
+ // instead of tenant-aware login page
+ response.sendRedirect(context + "/carbon/admin/login.jsp");
+ log.debug("Redirecting to /carbon/admin/login.jsp");
+ return false;
+ }
+ log.debug("Skipping security checks");
+ return true;
+ }
+
+ /**
+ *
+ * @param requestedURI
+ * @return
+ */
+ protected static String addNewContext(String requestedURI) {
+ String tmp = requestedURI;
+ String customWarContext = "";
+ if (requestedURI.startsWith("/carbon") && !(requestedURI.startsWith("/carbon/carbon/"))) {
+ // one can name the folder as 'carbon'
+ requestedURI = tmp;
+ } else if (requestedURI.indexOf("filedownload") == -1
+ && requestedURI.indexOf("fileupload") == -1) {
+ // replace first context
+ String tmp1 = tmp.replaceFirst("/", "");
+ int end = tmp1.indexOf('/');
+ if (end > -1) {
+ customWarContext = tmp1.substring(0, end);
+ // one can rename the war file as 'registry'.
+ // This will conflict with our internal 'registry' context
+ if (!(requestedURI.startsWith("/registry/registry/"))
+ && !(requestedURI.startsWith("/registry/carbon/"))
+ && (customWarContext.equals("registry")
+ || customWarContext.equals("gadgets") || customWarContext
+ .equals("social"))) {
+ requestedURI = tmp;
+ } else {
+ requestedURI = tmp.substring(end + 1);
+ }
+ }
+ }
+
+ return requestedURI;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6b1dba58/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUIMessage.java
----------------------------------------------------------------------
diff --git a/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUIMessage.java b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUIMessage.java
new file mode 100644
index 0000000..c73519c
--- /dev/null
+++ b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUIMessage.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed 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.ui;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.Serializable;
+
+public class CarbonUIMessage implements Serializable {
+
+ private static final long serialVersionUID = 7464385412679479148L;
+
+ public static final String ID = "carbonUIMessage";
+ public static final String INFO = "info";
+ public static final String ERROR = "error";
+ public static final String WARNING = "warning";
+
+ private String message;
+ private String messageType;
+ private Exception exception;
+ private boolean showStackTrace = true;
+
+ /**
+ * TODO: Make this constructor private
+ */
+ public CarbonUIMessage(String message, String messageType) {
+ this.message = message;
+ this.messageType = messageType;
+ }
+
+ /**
+ * TODO: Make this constructor private
+ */
+ public CarbonUIMessage(String message, String messageType, Exception exception) {
+ this.message = message;
+ this.messageType = messageType;
+ this.exception = exception;
+ }
+
+ /**
+ * TODO: Make this constructor private
+ */
+ public CarbonUIMessage(String message, String messageType, Exception exception,
+ boolean showStackTrace) {
+ this.message = message;
+ this.messageType = messageType;
+ this.exception = exception;
+ this.showStackTrace = showStackTrace;
+ }
+
+ public String getMessageType() {
+ return messageType;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public Exception getException(){
+ return exception;
+ }
+
+ public void setException(Exception exception){
+ this.exception = exception;
+ }
+
+ public boolean isShowStackTrace() {
+ return showStackTrace;
+ }
+
+ public void setShowStackTrace(boolean showStackTrace) {
+ this.showStackTrace = showStackTrace;
+ }
+
+ /**
+ * Creates CarbonUIMessage, set it to the session and redirect it to the given url
+ *
+ * @param message meesage to be displayed
+ * @param messageType info, warning, error
+ * @param request
+ * @param response
+ * @param urlToRedirect
+ */
+ public static void sendCarbonUIMessage(String message, String messageType, HttpServletRequest request,
+ HttpServletResponse response, String urlToRedirect) throws IOException {
+ CarbonUIMessage carbonMessage = new CarbonUIMessage(message, messageType);
+ request.getSession().setAttribute(CarbonUIMessage.ID, carbonMessage);
+ response.sendRedirect(urlToRedirect);
+ }
+
+ /***
+ * Creates error CarbonUIMessage, set it to the session and redirect it to the given url with the exception object
+ * @param message
+ * @param messageType
+ * @param request
+ * @param response
+ * @param urlToRedirect
+ * @param exception
+ * @return
+ * @throws IOException
+ */
+ public static CarbonUIMessage sendCarbonUIMessage(String message, String messageType,
+ HttpServletRequest request, HttpServletResponse response,
+ String urlToRedirect, Exception exception) throws IOException {
+ CarbonUIMessage carbonMessage = new CarbonUIMessage(message, messageType, exception);
+ request.getSession().setAttribute(CarbonUIMessage.ID, carbonMessage);
+ response.sendRedirect(urlToRedirect);
+ return carbonMessage;
+ }
+
+ /**
+ * Creates CarbonUIMessage, set it to the session
+ * @param message
+ * @param messageType
+ * @param request
+ */
+ public static void sendCarbonUIMessage(String message, String messageType, HttpServletRequest request) {
+ CarbonUIMessage carbonMessage = new CarbonUIMessage(message, messageType);
+ request.getSession().setAttribute(CarbonUIMessage.ID, carbonMessage);
+ }
+
+ /**
+ * Creates error CarbonUIMessage, set it to the session
+ * @param message
+ * @param messageType
+ * @param request
+ * @param exception
+ */
+ public static void sendCarbonUIMessage(String message, String messageType,
+ HttpServletRequest request, Exception exception) {
+ CarbonUIMessage carbonMessage = new CarbonUIMessage(message, messageType, exception);
+ request.getSession().setAttribute(CarbonUIMessage.ID, carbonMessage);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6b1dba58/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUIUtil.java
----------------------------------------------------------------------
diff --git a/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUIUtil.java b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUIUtil.java
new file mode 100644
index 0000000..711198b
--- /dev/null
+++ b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/CarbonUIUtil.java
@@ -0,0 +1,469 @@
+/*
+ * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed 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.ui;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.base.api.ServerConfigurationService;
+import org.wso2.carbon.ui.deployment.beans.CarbonUIDefinitions;
+import org.wso2.carbon.ui.deployment.beans.Menu;
+import org.wso2.carbon.ui.internal.CarbonUIServiceComponent;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.ConfigurationContextService;
+import org.wso2.carbon.utils.NetworkUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+/**
+ * Utility class for Carbon UI
+ */
+public class CarbonUIUtil {
+ public static final String QUERY_PARAM_LOCALE = "locale";
+ public static final String SESSION_PARAM_LOCALE = "custom_locale";
+ private static Log log = LogFactory.getLog(CarbonUIUtil.class);
+ private static BundleContext bundleContext = null;
+
+ //To store the product specific params
+ private static HashMap productParams = new HashMap();
+
+ /**
+ * Get a proxy object to the business logic implementation class.
+ * <p/>
+ * This proxy could be a handle to an OSGi service or a Web services client
+ *
+ * @param clientClassObject Web services client
+ * @param osgiObjectClass OSGi service class
+ * @param session The HTTP Session
+ * @return Proxy object
+ * @deprecated Do not use this method. Simply use the relevant client.
+ */
+ public static Object getServerProxy(Object clientClassObject,
+ Class osgiObjectClass,
+ HttpSession session) {
+ return clientClassObject;
+ }
+
+ public static void setBundleContext(BundleContext context) {
+ bundleContext = context;
+ }
+
+ public static BundleContext getBundleContext() {
+ return bundleContext;
+ }
+
+ public static String getIndexPageURL(ServerConfigurationService serverConfig) {
+ return serverConfig.getFirstProperty(CarbonConstants.INDEX_PAGE_URL);
+ }
+
+ public static String getIndexPageURL(ServletContext servletContext, HttpSession httpSession) {
+ String url;
+ Object obj = httpSession.getAttribute(CarbonConstants.INDEX_PAGE_URL);
+ if (obj != null && obj instanceof String) {
+ // Index Page URL is present in the servlet session
+ url = (String) obj;
+ } else {
+ url = (String) servletContext.getAttribute(CarbonConstants.INDEX_PAGE_URL);
+ }
+ return url;
+ }
+
+ public static String getServerURL(ServerConfigurationService serverConfig) {
+ ConfigurationContext serverCfgCtx =
+ CarbonUIServiceComponent.getConfigurationContextService().getServerConfigContext();
+ return CarbonUtils.getServerURL(serverConfig, serverCfgCtx);
+ }
+
+ public static String getServerURL(ServletContext servletContext, HttpSession httpSession) {
+ return CarbonUtils.getServerURL(servletContext, httpSession,
+ CarbonUIServiceComponent.
+ getConfigurationContextService().getServerConfigContext());
+ }
+
+ public static boolean isSuperTenant(HttpServletRequest request) {
+ return request.getSession().getAttribute(MultitenantConstants.IS_SUPER_TENANT) != null &&
+ request.getSession().getAttribute(MultitenantConstants.IS_SUPER_TENANT)
+ .equals(Boolean.toString(true));
+ }
+
+ public static String https2httpURL(String url) {
+ if (url.indexOf("${carbon.https.port}") != -1) {
+ String httpPort = CarbonUtils.getTransportPort(CarbonUIServiceComponent
+ .getConfigurationContextService(), "http")
+ + "";
+ url = url.replace("${carbon.https.port}", httpPort);
+ } else {
+ // TODO: This is a hack to gaurd against the above if condition failing.
+ // Need to dig into the root of the problem
+ url = url.replace("https", "http");
+ String httpsPort = CarbonUtils.getTransportPort(CarbonUIServiceComponent
+ .getConfigurationContextService(), "https")
+ + "";
+ String httpPort = CarbonUtils.getTransportPort(CarbonUIServiceComponent
+ .getConfigurationContextService(), "http")
+ + "";
+ url = url.replace(httpsPort, httpPort);
+ }
+ return url;
+ }
+
+ /**
+ * Returns url to admin console. eg: https://192.168.1.201:9443/wso2/carbon
+ *
+ * @param request The HTTPServletRequest
+ * @return The URL of the Admin Console
+ */
+ public static String getAdminConsoleURL(HttpServletRequest request) {
+
+ // Hostname
+ String hostName = "localhost";
+ try {
+ hostName = NetworkUtils.getMgtHostName();
+ } catch (Exception ignored) {
+ }
+
+ // HTTPS port
+ String mgtConsoleTransport = CarbonUtils.getManagementTransport();
+ ConfigurationContextService configContextService = CarbonUIServiceComponent
+ .getConfigurationContextService();
+ int httpsPort = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
+ int httpsProxyPort =
+ CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
+ mgtConsoleTransport);
+
+ // Context
+ String context = request.getContextPath();
+ if ("/".equals(context)) {
+ context = "";
+ }
+
+ if (httpsPort == -1) {
+ return null;
+ }
+
+ String adminConsoleURL = null;
+ String enableHTTPAdminConsole = CarbonUIServiceComponent.getServerConfiguration()
+ .getFirstProperty(CarbonConstants.ENABLE_HTTP_ADMIN_CONSOLE);
+
+ if (enableHTTPAdminConsole != null
+ && "true".equalsIgnoreCase(enableHTTPAdminConsole.trim())) {
+ int httpPort = CarbonUtils.getTransportPort(
+ CarbonUIServiceComponent.getConfigurationContextService(), "http");
+ adminConsoleURL = "http://" + hostName + ":" + httpPort + context + "/carbon/";
+ } else {
+ adminConsoleURL = "https://" + hostName + ":"
+ + (httpsProxyPort != -1 ? httpsProxyPort : httpsPort) + context + "/carbon/";
+ }
+
+ return adminConsoleURL;
+ }
+
+ /**
+ * Returns url to admin console.
+ *
+ * @param context Webapp context root of the Carbon webapp
+ * @return The URL of the Admin Console
+ */
+ public static String getAdminConsoleURL(String context) {
+ // Hostname
+ String hostName = "localhost";
+ try {
+ hostName = NetworkUtils.getMgtHostName();
+ } catch (Exception ignored) {
+ }
+
+ // HTTPS port
+ String mgtConsoleTransport = CarbonUtils.getManagementTransport();
+ ConfigurationContextService configContextService = CarbonUIServiceComponent
+ .getConfigurationContextService();
+ int httpsPort = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
+ int httpsProxyPort =
+ CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
+ mgtConsoleTransport);
+ // Context
+ if ("/".equals(context)) {
+ context = "";
+ }
+ return "https://" + hostName + ":" + (httpsProxyPort != -1? httpsProxyPort : httpsPort) +
+ context + "/carbon/";
+ }
+
+ /**
+ * Get a ServerConfiguration Property
+ *
+ * @param propertyName Name of the property
+ * @return the property
+ */
+ public static String getServerConfigurationProperty(String propertyName) {
+ try {
+ ServerConfigurationService serverConfig = CarbonUIServiceComponent.getServerConfiguration();
+ return serverConfig.getFirstProperty(propertyName);
+ } catch (Exception e) {
+ String msg = "ServerConfiguration Service not available";
+ log.error(msg, e);
+ }
+
+ return null;
+ }
+
+ public static boolean isContextRegistered(ServletConfig config, String context) {
+ URL url;
+ try {
+ url = config.getServletContext().getResource(context);
+ } catch (MalformedURLException e) {
+ return false;
+ }
+ if (url == null) {
+ return false;
+ } else if (url.toString().indexOf(context) != -1) {
+ return true;
+ }
+ return false;
+ }
+
+ public static Locale toLocale(String localeQuery){
+ String localeInfo[] = localeQuery.split("_");
+ int size = localeInfo.length;
+ Locale locale;
+ switch (size){
+ case 2:
+ locale = new Locale(localeInfo[0],localeInfo[1]);
+ break;
+ case 3:
+ locale = new Locale(localeInfo[0],localeInfo[1],localeInfo[2]);
+ break;
+ default:
+ locale = new Locale(localeInfo[0]);
+ break;
+ }
+ return locale;
+ }
+
+ public static void setLocaleToSession (HttpServletRequest request)
+ {
+ if (request.getParameter(QUERY_PARAM_LOCALE) != null) {
+ request.getSession().setAttribute(CarbonUIUtil.SESSION_PARAM_LOCALE, request.getParameter(QUERY_PARAM_LOCALE));
+ }
+ }
+
+ public static Locale getLocaleFromSession (HttpServletRequest request)
+ {
+ if (request.getSession().getAttribute(SESSION_PARAM_LOCALE) != null) {
+ String custom_locale = request.getSession().getAttribute(SESSION_PARAM_LOCALE).toString();
+ return toLocale(custom_locale);
+
+ } else {
+ return request.getLocale();
+ }
+ }
+
+ /**
+ * Returns internationalized string for supplied key.
+ *
+ * @param key - key to look for
+ * @param i18nBundle - resource bundle
+ * @param language - language
+ * @return internationalized key value of key, if no value can be derived
+ */
+ public static String geti18nString(String key, String i18nBundle, String language) {
+ Locale locale = new Locale(language);
+ String text = geti18nString(key, i18nBundle, locale);
+ return text;
+ }
+
+ /**
+ * Returns internationalized string for supplied key.
+ *
+ * @param key - key to look for
+ * @param i18nBundle - resource bundle
+ * @param locale - locale
+ * @return internationalized key value of key, if no value can be derived
+ */
+ public static String geti18nString(String key, String i18nBundle, Locale locale) {
+ java.util.ResourceBundle resourceBundle = null;
+ if (i18nBundle != null) {
+ try {
+ resourceBundle = java.util.ResourceBundle.getBundle(i18nBundle, locale);
+ } catch (java.util.MissingResourceException e) {
+ if (log.isDebugEnabled()) {
+ log.debug("Cannot find resource bundle : " + i18nBundle + " for locale : "
+ + locale);
+ }
+ }
+ }
+ String text = key;
+ if (resourceBundle != null) {
+ String tmp = null;
+ try {
+ tmp = resourceBundle.getString(key);
+ } catch (java.util.MissingResourceException e) {
+ // Missing key should not be a blocking factor for UI rendering
+ if (log.isDebugEnabled()) {
+ log.debug("Cannot find resource for key :" + key);
+ }
+ }
+ if (tmp != null) {
+ text = tmp;
+ }
+ }
+ return text;
+ }
+
+ /**
+ * Removed menu item from current user's session. Only current user's menu
+ * items are effected.
+ *
+ * @param menuId
+ * @param request
+ * @see CarbonUIDefinitions#removeMenuDefinition(String)
+ */
+ public static void removeMenuDefinition(String menuId, HttpServletRequest request) {
+ // TODO : consider removing child menu items as well
+ ArrayList<Menu> modifiedMenuDefs = new ArrayList<Menu>();
+ Menu[] currentMenus = (Menu[]) request.getSession().getAttribute(
+ MenuAdminClient.USER_MENU_ITEMS);
+ boolean modified = false;
+ if (currentMenus != null) {
+ if (menuId != null && menuId.trim().length() > 0) {
+ for (int a = 0; a < currentMenus.length; a++) {
+ Menu menu = currentMenus[a];
+ if (menu != null) {
+ if (!menuId.equals(menu.getId())) {
+ modifiedMenuDefs.add(menu);
+ modified = true;
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Removing menu item : " + menuId);
+ }
+ }
+ }
+ }
+ if (modified) {
+ Menu[] newMenuDefs = new Menu[modifiedMenuDefs.size()];
+ newMenuDefs = modifiedMenuDefs.toArray(newMenuDefs);
+ request.getSession().setAttribute(MenuAdminClient.USER_MENU_ITEMS, newMenuDefs);
+ }
+ }
+ }
+ }
+
+ public static String getBundleResourcePath(String resourceName) {
+ if (resourceName == null || resourceName.length() == 0) {
+ return null;
+ }
+
+ String resourcePath = resourceName;
+ resourcePath = resourcePath.startsWith("/") ? resourcePath.substring(1) : resourcePath;
+ resourcePath = (resourcePath.lastIndexOf('/') != -1) ? resourcePath.substring(0,
+ resourcePath.indexOf('/')) : resourcePath;
+
+ return resourcePath;
+ }
+
+ /**
+ * This method is a helper method for checking UI permissions.
+ */
+ @SuppressWarnings("unchecked")
+ public static boolean isUserAuthorized(HttpServletRequest request, String resource) {
+ boolean isAuthorized = false;
+ List<String> permissions = (List<String>) request.getSession().getAttribute(
+ CarbonConstants.UI_USER_PERMISSIONS);
+ if (permissions == null) {
+ return false;
+ }
+
+ for (String permission : permissions) {
+ if (resource.startsWith(permission)) {
+ isAuthorized = true;
+ break;
+ }
+ }
+
+ return isAuthorized;
+ }
+
+ /**
+ * Method is used to retrive product xml params
+ *
+ * @param key = product xml key
+ * @return product xml value
+ */
+ public static Object getProductParam(String key) {
+ return productParams.get(key);
+ }
+
+ public static void setProductParam(String key, Object value) {
+ productParams.put(key, value);
+ }
+
+ /**
+ * Returns home page location for "Home" link in Carbon UI menu.
+ * If defaultHomePage property is available in product.xml this method will return it and if not it'll return
+ * default ../admin/index.jsp
+ *
+ * @return home page location
+ */
+ public static String getHomePage() {
+ Object homePage;
+ if ((homePage = getDefaultHomePageProductParam())
+ != null) {
+ String homePageLocation = (String) homePage;
+ if (!homePageLocation.startsWith("/")) {
+ // it is assumed that homepage location is provided as a relative path starting
+ // from carbon context. This is to support the re-direction url at the login.
+ // Therefore here we fix the location to suit the homepage link of the product.
+ homePageLocation = "../../" + homePageLocation;
+ }
+ return homePageLocation;
+ }
+
+ return CarbonConstants.CARBON_UI_DEFAULT_HOME_PAGE;
+
+ }
+
+ public static String removeTenantSpecificStringsFromURL(String requestURL) {
+ if (requestURL.contains("/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/")) {
+ int tenantPrefixIndex = requestURL.lastIndexOf("/" +
+ MultitenantConstants.TENANT_AWARE_URL_PREFIX +
+ "/");
+ requestURL = requestURL.substring(tenantPrefixIndex +
+ MultitenantConstants.TENANT_AWARE_URL_PREFIX.length() +
+ 2);
+ // bypassing tenantDomain part
+ int pageUrlIndex = requestURL.indexOf('/');
+ requestURL = requestURL.substring(pageUrlIndex);
+ }
+ return requestURL;
+ }
+
+ private static Object getDefaultHomePageProductParam() {
+ return getProductParam(CarbonConstants.PRODUCT_XML_WSO2CARBON + CarbonConstants.DEFAULT_HOME_PAGE);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6b1dba58/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/ComponentDeployer.java
----------------------------------------------------------------------
diff --git a/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/ComponentDeployer.java b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/ComponentDeployer.java
new file mode 100644
index 0000000..0347906
--- /dev/null
+++ b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/ComponentDeployer.java
@@ -0,0 +1,189 @@
+/*
+* Copyright (c) 2005-2010, 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.ui;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.Bundle;
+import org.wso2.carbon.CarbonException;
+import org.wso2.carbon.ui.deployment.beans.Component;
+import org.wso2.carbon.ui.deployment.beans.Menu;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.transform.TransformerException;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.wso2.carbon.CarbonConstants.COMPONENT_ELE;
+import static org.wso2.carbon.CarbonConstants.GENERAL_ELE;
+import static org.wso2.carbon.CarbonConstants.JS_FILES_ELE;
+import static org.wso2.carbon.CarbonConstants.TAG_LIBS_ELE;
+import static org.wso2.carbon.ui.Utils.transform;
+
+/**
+ * Deploy the component
+ */
+public class ComponentDeployer {
+ /**
+ *
+ */
+ private final String[] mainTemplateSuffixes =
+ new String[]{"script_header", "menu", "main_layout"};
+
+ /**
+ *
+ */
+ private static Log log = LogFactory.getLog(ComponentDeployer.class);
+
+ /**
+ *
+ */
+ private Bundle componentBundle;
+
+ /**
+ *
+ */
+ private static final Map<String, String> processedFileMap = new HashMap<String, String>();
+
+
+ public ComponentDeployer(Bundle componentBundle) {
+ this.componentBundle = componentBundle;
+ }
+
+ public void layout(Map<Long, Component> componentMap) throws CarbonException {
+ Collection<Component> componentCollection = componentMap.values();
+ OMFactory fac = OMAbstractFactory.getOMFactory();
+ OMElement componentEle = fac.createOMElement(new QName(COMPONENT_ELE));
+ OMElement tagLibsEle = fac.createOMElement(new QName(TAG_LIBS_ELE));
+ componentEle.addChild(tagLibsEle);
+ OMElement jsFilesEle = fac.createOMElement(new QName(JS_FILES_ELE));
+ OMElement generalEle = fac.createOMElement(new QName(GENERAL_ELE));
+ componentEle.addChild(jsFilesEle);
+ componentEle.addChild(generalEle);
+// for (Component component : componentCollection) {
+// constructIntermediateStruecte(component, tagLibsEle, jsFilesEle, fac);
+// }
+ //leveling the menus first before adding to ims
+ List<Menu> menuList = new ArrayList<Menu>();
+ for (Component component : componentCollection) {
+ menuList.addAll(component.getMenusList());
+ }
+ Collections.sort(menuList, new Comparator<Menu>() {
+ public int compare(Menu m1, Menu m2) {
+ return m1.compareTo(m2);
+ }
+ });
+// for (Menu menu : menuList) {
+// OMElement menuEle = fac.createOMElement(new QName(MENUE_ELE));
+// generalEle.addChild(menuEle);
+// Action action = menu.getAction();
+// menuEle.addAttribute(ACTION_REF_ATTR, action.getName(), fac.createOMNamespace("", ""));
+// menuEle.addAttribute(NAME_ATTR, menu.getName(), fac.createOMNamespace("", ""));
+// menuEle.addAttribute(LEVEL_ATTR, Integer.toString(menu.getLevel()),
+// fac.createOMNamespace("", ""));
+// }
+
+
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+
+ if(log.isDebugEnabled()){
+ log.debug("intermediate : " + componentEle);
+ }
+
+ try {
+ componentEle.serializeAndConsume(bos);
+ } catch (XMLStreamException e) {
+ e.printStackTrace();
+ throw new CarbonException(e);
+ }
+ byte[] bytes = bos.toByteArray();
+
+ try {
+ // Transform
+ for (String templatSuffix : mainTemplateSuffixes) {
+ String xslResourceName = "ui/" + templatSuffix + ".xsl";
+ URL xslResource = componentBundle.getResource(xslResourceName);
+ if (xslResource == null) {
+ throw new CarbonException(
+ xslResourceName + " is not avaiable in component bundle");
+ }
+ ByteArrayOutputStream jspBos = new ByteArrayOutputStream();
+ transform(new ByteArrayInputStream(bytes), xslResource.openStream(), jspBos);
+ processedFileMap
+ .put("web/" + templatSuffix + ".jsp", new String(jspBos.toByteArray()));
+ }
+ } catch (TransformerException e) {
+ e.printStackTrace();
+ throw new CarbonException(e);
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ throw new CarbonException(e);
+ } catch (IOException e) {
+ e.printStackTrace();
+ throw new CarbonException(e);
+ }
+
+
+ }
+
+ /**
+ * Processed map
+ *
+ * @param key key
+ * @return value
+ */
+ public static String getFragment(String key) {
+ return processedFileMap.get(key);
+ }
+
+// private void constructIntermediateStruecte(Component component,
+// OMElement tabLibsEle,
+// OMElement jsFilesEle,
+// OMFactory fac) {
+// String effectivePath = component.getName() + "/" + component.getVersion() + "/";
+// List<TagLib> tagLibList = component.getTagLibList();
+// List<String> jsFilesList = component.getJsFilesList();
+// for (TagLib tagLib : tagLibList) {
+// OMElement tagLibEle = fac.createOMElement(new QName(TAG_LIB_ELE));
+// tagLibEle.addAttribute(URL_ATTR, tagLib.getUrl(), fac.createOMNamespace("", ""));
+// tagLibEle.addAttribute(PREFIX_ATTR, tagLib.getPrefix(), fac.createOMNamespace("", ""));
+// tabLibsEle.addChild(tagLibEle);
+// }
+// for (String fileName : jsFilesList) {
+// OMElement fileNameEle = fac.createOMElement(new QName(JS_FILE_ELE));
+// fileNameEle.setText(effectivePath + fileName);
+// jsFilesEle.addChild(fileNameEle);
+// }
+//
+// }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6b1dba58/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultAuthenticatorCredentials.java
----------------------------------------------------------------------
diff --git a/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultAuthenticatorCredentials.java b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultAuthenticatorCredentials.java
new file mode 100644
index 0000000..c651bb8
--- /dev/null
+++ b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultAuthenticatorCredentials.java
@@ -0,0 +1,22 @@
+package org.wso2.carbon.ui;
+
+public class DefaultAuthenticatorCredentials {
+
+ private String userName;
+ private String password;
+
+ public DefaultAuthenticatorCredentials(String userName, String password) {
+ super();
+ this.userName = userName;
+ this.password = password;
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6b1dba58/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultCarbonAuthenticator.java
----------------------------------------------------------------------
diff --git a/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultCarbonAuthenticator.java b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultCarbonAuthenticator.java
new file mode 100644
index 0000000..c84bb83
--- /dev/null
+++ b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultCarbonAuthenticator.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 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.ui;
+
+import java.util.Map;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.authenticator.proxy.AuthenticationAdminClient;
+import org.wso2.carbon.authenticator.stub.RememberMeData;
+import org.wso2.carbon.core.common.AuthenticationException;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.ServerConstants;
+
+/**
+ * Default implementation of CarbonUIAuthenticator.
+ */
+public class DefaultCarbonAuthenticator extends BasicAuthUIAuthenticator {
+
+ protected static final Log log = LogFactory.getLog(DefaultCarbonAuthenticator.class);
+
+ private static final String AUTHENTICATOR_NAME = "DefaultCarbonAuthenticator";
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean canHandle(HttpServletRequest request) {
+ // try to authenticate any request that comes
+ // least priority authenticator
+ String userName = request.getParameter(AbstractCarbonUIAuthenticator.USERNAME);
+ String password = request.getParameter(AbstractCarbonUIAuthenticator.PASSWORD);
+
+ if (!CarbonUtils.isRunningOnLocalTransportMode()) {
+ return false;
+ }
+
+ if (userName != null && password != null) {
+ return true;
+ }
+
+ // This is to login with Remember Me.
+ Cookie[] cookies = request.getCookies();
+ if (cookies != null) {
+ for (Cookie cookie : cookies) {
+ if (cookie.getName().equals(CarbonConstants.REMEMBER_ME_COOKE_NAME)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String doAuthentication(Object credentials, boolean isRememberMe, ServiceClient client,
+ HttpServletRequest request) throws AuthenticationException {
+
+ DefaultAuthenticatorCredentials defaultCredentials = (DefaultAuthenticatorCredentials) credentials;
+ // call AuthenticationAdmin, since BasicAuth are not validated for LocalTransport
+ AuthenticationAdminClient authClient;
+ try {
+ authClient = getAuthenticationAdminCient(request);
+ boolean isAutenticated = false;
+ if (isRememberMe && defaultCredentials.getUserName() != null
+ && defaultCredentials.getPassword() != null) {
+ RememberMeData rememberMe;
+ rememberMe = authClient.loginWithRememberMeOption(defaultCredentials.getUserName(),
+ defaultCredentials.getPassword(), "127.0.0.1");
+ isAutenticated = rememberMe.getAuthenticated();
+ if (isAutenticated) {
+ request.setAttribute(CarbonConstants.REMEMBER_ME_COOKIE_VALUE,
+ rememberMe.getValue());
+ request.setAttribute(CarbonConstants.REMEMBER_ME_COOKIE_AGE, new Integer(
+ rememberMe.getMaxAge()).toString());
+ return defaultCredentials.getUserName();
+ }
+ } else if (isRememberMe) {
+ // This is to login with Remember Me.
+ Cookie[] cookies = request.getCookies();
+ if (cookies != null) {
+ for (Cookie cookie : cookies) {
+ if (cookie.getName().equals(CarbonConstants.REMEMBER_ME_COOKE_NAME)) {
+ isAutenticated = authClient
+ .loginWithRememberMeCookie(cookie.getValue());
+ if (isAutenticated) {
+ String cookieValue = cookie.getValue();
+ return getUserNameFromCookie(cookieValue);
+ }
+ }
+ }
+ }
+ } else {
+ isAutenticated = authClient.login(defaultCredentials.getUserName(),
+ defaultCredentials.getPassword(), "127.0.0.1");
+ if (isAutenticated) {
+ return defaultCredentials.getUserName();
+ }
+ }
+
+ throw new AuthenticationException("Invalid user credentials.");
+
+ } catch (AxisFault e) {
+ throw new AuthenticationException(e.getMessage(), e);
+ }
+
+ }
+
+ /**
+ *
+ */
+ public void unauthenticate(Object object) throws Exception {
+ try {
+ getAuthenticationAdminCient(((HttpServletRequest) object)).logout();
+ } catch (Exception ignored) {
+ String msg = "Configuration context is null.";
+ log.error(msg);
+ throw new Exception(msg);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getAuthenticatorName() {
+ return AUTHENTICATOR_NAME;
+ }
+
+ /**
+ *
+ * @param request
+ * @return
+ * @throws AxisFault
+ */
+ private AuthenticationAdminClient getAuthenticationAdminCient(HttpServletRequest request)
+ throws AxisFault {
+ HttpSession session = request.getSession();
+ ServletContext servletContext = session.getServletContext();
+ String backendServerURL = request.getParameter("backendURL");
+ if (backendServerURL == null) {
+ backendServerURL = CarbonUIUtil.getServerURL(servletContext, request.getSession());
+ }
+ session.setAttribute(CarbonConstants.SERVER_URL, backendServerURL);
+
+ ConfigurationContext configContext = (ConfigurationContext) servletContext
+ .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+
+ String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_AUTH_TOKEN);
+
+ return new AuthenticationAdminClient(configContext, backendServerURL, cookie, session, true);
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public void handleRememberMe(Map transportHeaders, HttpServletRequest httpServletRequest)
+ throws AuthenticationException {
+ // Do nothing here. Already done.
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6b1dba58/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultComponentEntryHttpContext.java
----------------------------------------------------------------------
diff --git a/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultComponentEntryHttpContext.java b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultComponentEntryHttpContext.java
new file mode 100644
index 0000000..db7d199
--- /dev/null
+++ b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DefaultComponentEntryHttpContext.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed 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.ui;
+
+import org.eclipse.equinox.http.helper.BundleEntryHttpContext;
+import org.osgi.framework.Bundle;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ *
+ */
+public class DefaultComponentEntryHttpContext extends BundleEntryHttpContext {
+
+ private String bundlePath;
+
+ public DefaultComponentEntryHttpContext(Bundle bundle) {
+ super(bundle);
+ }
+
+ public DefaultComponentEntryHttpContext(Bundle bundle, String bundlePath) {
+ super(bundle, bundlePath);
+ this.bundlePath = bundlePath;
+ }
+
+ public URL getResource(String resourceName) {
+ URL url = super.getResource(resourceName);
+ if (url != null) {
+ return url;
+ } else {
+ if (bundlePath != null) {
+ resourceName = bundlePath + resourceName;
+ }
+ int lastSlash = resourceName.lastIndexOf('/');
+ if (lastSlash == -1) {
+ return null;
+ }
+ String path = resourceName.substring(0, lastSlash);
+ if (path.length() == 0) {
+ path = "/";
+ }
+ String file = resourceName.substring(lastSlash + 1);
+ if (file.endsWith(".js") && isListed(file)) {
+ try {
+ return new URL("carbon://generate/" + file);
+ } catch (MalformedURLException e) {
+ return null;
+ }
+ }
+ return null;
+
+ }
+
+ }
+
+ /**
+ * TODO: fix this from a configuration file
+ *
+ * @param file
+ * @return
+ */
+ private boolean isListed(String file) {
+ return "global-params.js".equals(file);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6b1dba58/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DeploymentEngine.java
----------------------------------------------------------------------
diff --git a/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DeploymentEngine.java b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DeploymentEngine.java
new file mode 100644
index 0000000..497bbc4
--- /dev/null
+++ b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/DeploymentEngine.java
@@ -0,0 +1,98 @@
+/*
+* Copyright (c) 2005-2010, 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.ui;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.Bundle;
+import org.wso2.carbon.CarbonException;
+import org.wso2.carbon.ui.deployment.beans.Component;
+
+import javax.xml.stream.XMLStreamException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Dictionary;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import static org.wso2.carbon.ui.deployment.ComponentBuilder.build;
+
+/**
+ * Engine that process plugins
+ */
+public class DeploymentEngine {
+
+ /**
+ *
+ */
+ private Map<Long, Component> componentMap = new ConcurrentHashMap<Long, Component>();
+
+ /**
+ *
+ */
+ private ComponentDeployer componentDeployer;
+
+ /**
+ *
+ */
+ private static Log log = LogFactory.getLog(DeploymentEngine.class);
+
+ /**
+ *
+ */
+ private Bundle componentBundle;
+
+ public DeploymentEngine(Bundle componentBundle) {
+ this.componentBundle = componentBundle;
+ this.componentDeployer = new ComponentDeployer(componentBundle);
+ }
+
+
+ public void process(Bundle registeredBundle) {
+ try {
+ URL url = registeredBundle.getEntry("META-INF/component.xml");
+ if (url != null) {
+ //found a Carbon OSGi bundle that should amend for admin UI
+ Dictionary headers = registeredBundle.getHeaders();
+ String bundleName = (String) headers.get("Bundle-Name");
+ String bundleVersion = (String) headers.get("Bundle-Version");
+ InputStream inputStream = url.openStream();
+ Component component = build(inputStream,
+ bundleName,
+ bundleVersion,
+ registeredBundle.getBundleContext());
+ componentMap.put(registeredBundle.getBundleId(), component);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ log.error("", e);
+ } catch (XMLStreamException e) {
+ e.printStackTrace();
+ log.error("", e);
+ } catch (CarbonException e) {
+ e.printStackTrace();
+ log.error("", e);
+ }
+ }
+
+ public void layout() throws CarbonException {
+ componentDeployer.layout(componentMap);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6b1dba58/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/JSPContextFinder.java
----------------------------------------------------------------------
diff --git a/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/JSPContextFinder.java b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/JSPContextFinder.java
new file mode 100644
index 0000000..95a8430
--- /dev/null
+++ b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/JSPContextFinder.java
@@ -0,0 +1,193 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed 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.ui;
+
+import org.wso2.carbon.ui.internal.CarbonUIServiceComponent;
+
+import java.io.IOException;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+// This class is a slightly augmented copy of org.eclipse.core.runtime.internal.adaptor.ContextFinder
+// in particular basicFindClassLoaders has been altered to use PackageAdmin to determine if a class originated from
+// a bundle and to skip over the various JspClassloader classes.
+public class JSPContextFinder extends ClassLoader implements PrivilegedAction {
+ static final class Finder extends SecurityManager {
+ public Class[] getClassContext() {
+ return super.getClassContext();
+ }
+ }
+ //This is used to detect cycle that could be caused while delegating the loading to other classloaders
+ //It keeps track on a thread basis of the set of requested classes and resources
+ private static ThreadLocal cycleDetector = new ThreadLocal();
+ private static Finder contextFinder;
+ static {
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ contextFinder = new Finder();
+ return null;
+ }
+ });
+ }
+
+ public JSPContextFinder(ClassLoader contextClassLoader) {
+ super(contextClassLoader);
+ }
+
+ // Return a list of all classloaders on the stack that are neither the
+ // JSPContextFinder classloader nor the boot classloader. The last classloader
+ // in the list is either a bundle classloader or the framework's classloader
+ // We assume that the bootclassloader never uses the context classloader to find classes in itself.
+ List basicFindClassLoaders() {
+ Class[] stack = contextFinder.getClassContext();
+ ArrayList result = new ArrayList(1);
+ ClassLoader previousLoader = null;
+ for (int i = 1; i < stack.length; i++) {
+ ClassLoader tmp = stack[i].getClassLoader();
+ if (checkClass(stack[i]) && tmp != null && tmp != this) {
+ if (checkClassLoader(tmp) && previousLoader != tmp) {
+ result.add(tmp);
+ previousLoader = tmp;
+ }
+ // stop at the framework classloader or the first bundle classloader
+ if (CarbonUIServiceComponent.getBundle(stack[i]) != null) {
+ break;
+ }
+ }
+ }
+ return result;
+ }
+
+ private boolean checkClass(Class clazz) {
+ return clazz != JSPContextFinder.class &&
+ clazz != BundleProxyClassLoader.class &&
+ clazz != JspClassLoader.class;
+ }
+
+ // ensures that a classloader does not have the JSPContextFinder as part of the
+ // parent hierachy. A classloader which has the JSPContextFinder as a parent must
+ // not be used as a delegate, otherwise we endup in endless recursion.
+ private boolean checkClassLoader(ClassLoader classloader) {
+ if (classloader == null || classloader == getParent()) {
+ return false;
+ }
+ for (ClassLoader parent = classloader.getParent(); parent != null; parent = parent.getParent()) {
+ if (parent == this) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private List findClassLoaders() {
+ if (System.getSecurityManager() == null) {
+ return basicFindClassLoaders();
+ }
+ return (ArrayList) AccessController.doPrivileged(this);
+ }
+
+ public Object run() {
+ return basicFindClassLoaders();
+ }
+
+ //Return whether the request for loading "name" should proceed.
+ //False is returned when a cycle is being detected
+ private boolean startLoading(String name) {
+ Set classesAndResources = (Set) cycleDetector.get();
+ if (classesAndResources != null && classesAndResources.contains(name)) {
+ return false;
+ }
+
+ if (classesAndResources == null) {
+ classesAndResources = new HashSet(3);
+ cycleDetector.set(classesAndResources);
+ }
+ classesAndResources.add(name);
+ return true;
+ }
+
+ private void stopLoading(String name) {
+ ((Set) cycleDetector.get()).remove(name);
+ }
+
+ protected Class loadClass(String arg0, boolean arg1) throws ClassNotFoundException {
+ //Shortcut cycle
+ if (!startLoading(arg0)) {
+ throw new ClassNotFoundException(arg0);
+ }
+
+ try {
+ List toConsult = findClassLoaders();
+ for (Iterator loaders = toConsult.iterator(); loaders.hasNext();) {
+ try {
+ return ((ClassLoader) loaders.next()).loadClass(arg0);
+ } catch (ClassNotFoundException e) {
+ // go to the next class loader
+ }
+ }
+ return super.loadClass(arg0, arg1);
+ } finally {
+ stopLoading(arg0);
+ }
+ }
+
+ public URL getResource(String arg0) {
+ //Shortcut cycle
+ if (!startLoading(arg0)) {
+ return null;
+ }
+ try {
+ List toConsult = findClassLoaders();
+ for (Iterator loaders = toConsult.iterator(); loaders.hasNext();) {
+ URL result = ((ClassLoader) loaders.next()).getResource(arg0);
+ if (result != null) {
+ return result;
+ }
+ // go to the next class loader
+ }
+ return super.getResource(arg0);
+ } finally {
+ stopLoading(arg0);
+ }
+ }
+
+ protected Enumeration findResources(String arg0) throws IOException {
+ //Shortcut cycle
+ if (!startLoading(arg0)) {
+ return null;
+ }
+ try {
+ List toConsult = findClassLoaders();
+ for (Iterator loaders = toConsult.iterator(); loaders.hasNext();) {
+ Enumeration result = ((ClassLoader) loaders.next()).getResources(arg0);
+ if (result != null && result.hasMoreElements()) {
+ return result;
+ }
+ // go to the next class loader
+ }
+ return super.findResources(arg0);
+ } finally {
+ stopLoading(arg0);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6b1dba58/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/JspClassLoader.java
----------------------------------------------------------------------
diff --git a/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/JspClassLoader.java b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/JspClassLoader.java
new file mode 100644
index 0000000..31e8bb6
--- /dev/null
+++ b/dependencies/org.wso2.carbon.ui/src/main/java/org/wso2/carbon/ui/JspClassLoader.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed 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.ui;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.Constants;
+import org.wso2.carbon.ui.internal.CarbonUIServiceComponent;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.security.CodeSource;
+import java.security.PermissionCollection;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.StringTokenizer;
+
+/**
+ * Jasper requires that this class loader be an instance of URLClassLoader.
+ * At runtime it uses the URLClassLoader's getURLs method to find jar files that are in turn searched for TLDs. In a webapp
+ * these jar files would normally be located in WEB-INF/lib. In the OSGi context, this behaviour is provided by returning the
+ * URLs of the jar files contained on the Bundle-ClassPath. Other than jar file tld resources this classloader is not used for
+ * loading classes which should be done by the other contained class loaders.
+ * <p/>
+ * The rest of the ClassLoader is as follows:
+ * 1) Thread-ContextClassLoader (top - parent) -- see ContextFinder
+ * 2) Jasper Bundle
+ * 3) The Bundle referenced at JSPServlet creation
+ */
+public class JspClassLoader extends URLClassLoader {
+
+ private static final Bundle JASPERBUNDLE = CarbonUIServiceComponent.getBundle(JspServlet.class);
+ private static final ClassLoader PARENT = JspClassLoader.class.getClassLoader().getParent();
+ private static final String JAVA_PACKAGE = "java."; //$NON-NLS-1$
+ private static final ClassLoader EMPTY_CLASSLOADER = new ClassLoader(null) {
+ public URL getResource(String name) {
+ return null;
+ }
+
+ public Enumeration findResources(String name) throws IOException {
+ return new Enumeration() {
+ public boolean hasMoreElements() {
+ return false;
+ }
+
+ public Object nextElement() {
+ return null;
+ }
+ };
+ }
+
+ public Class loadClass(String name) throws ClassNotFoundException {
+ throw new ClassNotFoundException(name);
+ }
+ };
+
+ private PermissionCollection permissions;
+
+ public JspClassLoader(Bundle bundle, PermissionCollection permissions) {
+ super(new URL[0], new BundleProxyClassLoader(bundle, new BundleProxyClassLoader(
+ JASPERBUNDLE, new JSPContextFinder(EMPTY_CLASSLOADER))));
+ this.permissions = permissions;
+ addBundleClassPathJars(bundle);
+ }
+
+ private void addBundleClassPathJars(Bundle bundle) {
+ Dictionary headers = bundle.getHeaders();
+ String classPath = (String) headers.get(Constants.BUNDLE_CLASSPATH);
+ if (classPath != null) {
+ StringTokenizer tokenizer = new StringTokenizer(classPath, ","); //$NON-NLS-1$
+ while (tokenizer.hasMoreTokens()) {
+ String candidate = tokenizer.nextToken().trim();
+ if (candidate.endsWith(".jar")) { //$NON-NLS-1$
+ URL entry = bundle.getEntry(candidate);
+ if (entry != null) {
+ URL jarEntryURL;
+ try {
+ jarEntryURL = new URL(
+ "jar:" + entry.toString() + "!/"); //$NON-NLS-1$ //$NON-NLS-2$
+ super.addURL(jarEntryURL);
+ } catch (MalformedURLException e) {
+ // TODO should log this.
+ }
+ }
+ }
+ }
+ }
+ }
+
+ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
+ if (PARENT != null && name.startsWith(JAVA_PACKAGE)) {
+ return PARENT.loadClass(name);
+ }
+ return super.loadClass(name, resolve);
+ }
+
+ // Classes should "not" be loaded by this classloader from the URLs - it is just used for TLD resource discovery.
+ protected Class findClass(String name) throws ClassNotFoundException {
+ throw new ClassNotFoundException(name);
+ }
+
+ protected PermissionCollection getPermissions(CodeSource codesource) {
+ return permissions;
+ }
+}