public GovImpactAnalysisDataProcessor( ServletConfig config, HttpSession session, HttpServletRequest request) throws AxisFault { client = new GovImpactAdminServiceClient(config, session, request); serverURL = CarbonUIUtil.getAdminConsoleURL( CarbonUIUtil.getServerConfigurationProperty("WebContextRoot")); }
public ManageGenericArtifactServiceClient(ServletConfig config, HttpSession session) throws RegistryException { String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); ConfigurationContext configContext = (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); epr = backendServerURL + "ManageGenericArtifactService"; try { stub = new ManageGenericArtifactServiceStub(configContext, epr); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (AxisFault axisFault) { String msg = "Failed to initiate ManageGenericArtifactServiceClient. " + axisFault.getMessage(); log.error(msg, axisFault); throw new RegistryException(msg, axisFault); } }
/** * Prompts user a notification with the status and message * * @param req * @param resp * @throws ServletException * @throws IOException */ private void sendNotification( String errorResp, String status, String message, String acUrl, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String redirectURL = CarbonUIUtil.getAdminConsoleURL(req); redirectURL = redirectURL.replace("samlsso/carbon/", "authenticationendpoint/samlsso_notification.do"); // TODO Send status codes rather than full messages in the GET request String queryParams = "?" + SAMLSSOConstants.STATUS + "=" + URLEncoder.encode(status, "UTF-8") + "&" + SAMLSSOConstants.STATUS_MSG + "=" + URLEncoder.encode(message, "UTF-8"); if (errorResp != null) { queryParams += "&" + SAMLSSOConstants.SAML_RESP + "=" + URLEncoder.encode(errorResp, "UTF-8"); } if (acUrl != null) { queryParams += "&" + SAMLSSOConstants.ASSRTN_CONSUMER_URL + "=" + URLEncoder.encode(acUrl, "UTF-8"); } resp.sendRedirect(redirectURL + queryParams); }
public static ReportResourceSupplierClient getInstance(ServletConfig config, HttpSession session) throws AxisFault { String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); ConfigurationContext configContext = (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); return new ReportResourceSupplierClient(cookie, backendServerURL, configContext); }
public static EventBuilderAdminServiceStub getEventBuilderAdminService( ServletConfig config, HttpSession session, HttpServletRequest request) throws AxisFault { ConfigurationContext configContext = (ConfigurationContext) config.getServletContext() .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); //Server URL which is defined in the server.xml String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session) + "EventBuilderAdminService.EventBuilderAdminServiceHttpsSoap12Endpoint"; EventBuilderAdminServiceStub stub = new EventBuilderAdminServiceStub(configContext, serverURL); String cookie = (String) session.getAttribute(org.wso2.carbon.utils.ServerConstants.ADMIN_SERVICE_COOKIE); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); return stub; }
/** * This is override because of query string values hard coded and input values validations are not * required. * * @param request * @param response * @param context * @throws AuthenticationFailedException */ @Override protected void initiateAuthenticationRequest( HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { try { Map<String, String> authenticatorProperties = context.getAuthenticatorProperties(); if (authenticatorProperties != null) { String clientId = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_ID); String authorizationEP; if (getAuthorizationServerEndpoint(authenticatorProperties) != null) { authorizationEP = getAuthorizationServerEndpoint(authenticatorProperties); } else { authorizationEP = authenticatorProperties.get(OIDCAuthenticatorConstants.OAUTH2_AUTHZ_URL); } String callBackUrl = authenticatorProperties.get(GoogleOAuth2AuthenticationConstant.CALLBACK_URL); if (log.isDebugEnabled()) { log.debug("Google-callback-url : " + callBackUrl); } if (callBackUrl == null) { callBackUrl = CarbonUIUtil.getAdminConsoleURL(request); callBackUrl = callBackUrl.replace("commonauth/carbon/", "commonauth"); } String state = context.getContextIdentifier() + "," + OIDCAuthenticatorConstants.LOGIN_TYPE; state = getState(state, authenticatorProperties); OAuthClientRequest authzRequest; // This is the query string need to send in order to get email and // profile String queryString = GoogleOAuth2AuthenticationConstant.QUERY_STRING; authzRequest = OAuthClientRequest.authorizationLocation(authorizationEP) .setClientId(clientId) .setRedirectURI(callBackUrl) .setResponseType(OIDCAuthenticatorConstants.OAUTH2_GRANT_TYPE_CODE) .setState(state) .buildQueryMessage(); String loginPage = authzRequest.getLocationUri(); String domain = request.getParameter("domain"); if (domain != null) { loginPage = loginPage + "&fidp=" + domain; } if (queryString != null) { if (!queryString.startsWith("&")) { loginPage = loginPage + "&" + queryString; } else { loginPage = loginPage + queryString; } } response.sendRedirect(loginPage); } else { if (log.isDebugEnabled()) { log.debug("Error while retrieving properties. Authenticator Properties cannot be null"); } throw new AuthenticationFailedException( "Error while retrieving properties. Authenticator Properties cannot be null"); } } catch (IOException e) { throw new AuthenticationFailedException("Exception while sending to the login page", e); } catch (OAuthSystemException e) { throw new AuthenticationFailedException( "Exception while building authorization code request", e); } }
/** * this method are overridden for extra claim request to google end-point * * @param request * @param response * @param context * @throws AuthenticationFailedException */ @Override protected void processAuthenticationResponse( HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { try { Map<String, String> authenticatorProperties = context.getAuthenticatorProperties(); String clientId = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_ID); String clientSecret = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_SECRET); String tokenEndPoint; if (getTokenEndpoint(authenticatorProperties) != null) { tokenEndPoint = getTokenEndpoint(authenticatorProperties); } else { tokenEndPoint = authenticatorProperties.get(OIDCAuthenticatorConstants.OAUTH2_TOKEN_URL); } String callBackUrl = authenticatorProperties.get(GoogleOAuth2AuthenticationConstant.CALLBACK_URL); log.debug("callBackUrl : " + callBackUrl); if (callBackUrl == null) { callBackUrl = CarbonUIUtil.getAdminConsoleURL(request); callBackUrl = callBackUrl.replace("commonauth/carbon/", "commonauth"); } @SuppressWarnings({"unchecked"}) Map<String, String> paramValueMap = (Map<String, String>) context.getProperty("oidc:param.map"); if (paramValueMap != null && paramValueMap.containsKey("redirect_uri")) { callBackUrl = paramValueMap.get("redirect_uri"); } OAuthAuthzResponse authzResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request); String code = authzResponse.getCode(); OAuthClientRequest accessRequest = null; accessRequest = getAccessRequest(tokenEndPoint, clientId, clientSecret, callBackUrl, code); // create OAuth client that uses custom http client under the hood OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); OAuthClientResponse oAuthResponse = null; oAuthResponse = getOAuthResponse(accessRequest, oAuthClient, oAuthResponse); // TODO : return access token and id token to framework String accessToken = ""; String idToken = ""; if (oAuthResponse != null) { accessToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN); idToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ID_TOKEN); } if (accessToken != null && (idToken != null || !requiredIDToken(authenticatorProperties))) { context.setProperty(OIDCAuthenticatorConstants.ACCESS_TOKEN, accessToken); if (idToken != null) { context.setProperty(OIDCAuthenticatorConstants.ID_TOKEN, idToken); String base64Body = idToken.split("\\.")[1]; byte[] decoded = Base64.decodeBase64(base64Body.getBytes()); String json = new String(decoded, Charset.forName("utf-8")); if (log.isDebugEnabled()) { log.debug("Id token json string : " + json); } Map<String, Object> jsonObject = JSONUtils.parseJSON(json); if (jsonObject != null) { Map<ClaimMapping, String> claims = getSubjectAttributes(oAuthResponse); String authenticatedUser = (String) jsonObject.get(OIDCAuthenticatorConstants.Claim.EMAIL); AuthenticatedUser authenticatedUserObj = AuthenticatedUser.createFederateAuthenticatedUserFromSubjectIdentifier( authenticatedUser); authenticatedUserObj.setUserAttributes(claims); context.setSubject(authenticatedUserObj); } else { if (log.isDebugEnabled()) { log.debug("Decoded json object is null"); } throw new AuthenticationFailedException("Decoded json object is null"); } } else { if (log.isDebugEnabled()) { log.debug("Authentication Failed"); } throw new AuthenticationFailedException("Authentication Failed"); } } else { throw new AuthenticationFailedException("Authentication Failed"); } } catch (OAuthProblemException e) { throw new AuthenticationFailedException("Error occurred while acquiring access token", e); } catch (JSONException e) { throw new AuthenticationFailedException("Error occurred while parsing json object", e); } }
public void _jspService( final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); org.apache.jasper.runtime.JspRuntimeLibrary.include( request, response, "../dialog/display_messages.jsp", out, false); out.write('\n'); out.write('\n'); // fmt:bundle org.apache.taglibs.standard.tag.rt.fmt.BundleTag _jspx_th_fmt_005fbundle_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.BundleTag) _005fjspx_005ftagPool_005ffmt_005fbundle_0026_005fbasename.get( org.apache.taglibs.standard.tag.rt.fmt.BundleTag.class); _jspx_th_fmt_005fbundle_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fbundle_005f0.setParent(null); // /admin/index.jsp(28,0) name = basename type = null reqTime = true required = true fragment // = false deferredValue = false expectedTypeName = null deferredMethod = false // methodSignature = null _jspx_th_fmt_005fbundle_005f0.setBasename("org.wso2.carbon.i18n.Resources"); int _jspx_eval_fmt_005fbundle_005f0 = _jspx_th_fmt_005fbundle_005f0.doStartTag(); if (_jspx_eval_fmt_005fbundle_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { if (_jspx_eval_fmt_005fbundle_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.pushBody(); _jspx_th_fmt_005fbundle_005f0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out); _jspx_th_fmt_005fbundle_005f0.doInitBody(); } do { out.write('\n'); out.write('\n'); Object param = session.getAttribute("authenticated"); String passwordExpires = (String) session.getAttribute(ServerConstants.PASSWORD_EXPIRATION); boolean loggedIn = false; if (param != null) { loggedIn = (Boolean) param; } boolean serverAdminComponentFound = CarbonUIUtil.isContextRegistered(config, "/server-admin/"); if (CharacterEncoder.getSafeText(request.getParameter("skipLoginPage")) != null) { response.sendRedirect("../admin/login_action.jsp"); return; } out.write("\n"); out.write(" <div id=\"middle\">\n"); out.write(" "); String serverName = CarbonUIUtil.getServerConfigurationProperty("Name"); out.write("\n"); out.write(" <h2>\n"); out.write(" "); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey.get( org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f0.setParent( (javax.servlet.jsp.tagext.Tag) _jspx_th_fmt_005fbundle_005f0); // /admin/index.jsp(52,12) name = key type = null reqTime = true required = false fragment // = false deferredValue = false expectedTypeName = null deferredMethod = false // methodSignature = null _jspx_th_fmt_005fmessage_005f0.setKey("carbon.server.home"); int _jspx_eval_fmt_005fmessage_005f0 = _jspx_th_fmt_005fmessage_005f0.doStartTag(); if (_jspx_eval_fmt_005fmessage_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { if (_jspx_eval_fmt_005fmessage_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.pushBody(); _jspx_th_fmt_005fmessage_005f0.setBodyContent( (javax.servlet.jsp.tagext.BodyContent) out); _jspx_th_fmt_005fmessage_005f0.doInitBody(); } do { out.write("\n"); out.write(" "); // fmt:param org.apache.taglibs.standard.tag.rt.fmt.ParamTag _jspx_th_fmt_005fparam_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.ParamTag) _005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody.get( org.apache.taglibs.standard.tag.rt.fmt.ParamTag.class); _jspx_th_fmt_005fparam_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fparam_005f0.setParent( (javax.servlet.jsp.tagext.Tag) _jspx_th_fmt_005fmessage_005f0); // /admin/index.jsp(53,16) name = value type = null reqTime = true required = false // fragment = false deferredValue = false expectedTypeName = null deferredMethod = // false methodSignature = null _jspx_th_fmt_005fparam_005f0.setValue(serverName); int _jspx_eval_fmt_005fparam_005f0 = _jspx_th_fmt_005fparam_005f0.doStartTag(); if (_jspx_th_fmt_005fparam_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody.reuse( _jspx_th_fmt_005fparam_005f0); return; } _005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody.reuse( _jspx_th_fmt_005fparam_005f0); out.write("\n"); out.write(" "); int evalDoAfterBody = _jspx_th_fmt_005fmessage_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); if (_jspx_eval_fmt_005fmessage_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.popBody(); } } if (_jspx_th_fmt_005fmessage_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey.reuse( _jspx_th_fmt_005fmessage_005f0); return; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey.reuse( _jspx_th_fmt_005fmessage_005f0); out.write("\n"); out.write(" </h2>\n"); out.write("\n"); out.write(" <p>\n"); out.write(" "); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f1 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey.get( org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f1.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f1.setParent( (javax.servlet.jsp.tagext.Tag) _jspx_th_fmt_005fbundle_005f0); // /admin/index.jsp(58,12) name = key type = null reqTime = true required = false fragment // = false deferredValue = false expectedTypeName = null deferredMethod = false // methodSignature = null _jspx_th_fmt_005fmessage_005f1.setKey("carbon.console.welcome"); int _jspx_eval_fmt_005fmessage_005f1 = _jspx_th_fmt_005fmessage_005f1.doStartTag(); if (_jspx_eval_fmt_005fmessage_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { if (_jspx_eval_fmt_005fmessage_005f1 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.pushBody(); _jspx_th_fmt_005fmessage_005f1.setBodyContent( (javax.servlet.jsp.tagext.BodyContent) out); _jspx_th_fmt_005fmessage_005f1.doInitBody(); } do { out.write("\n"); out.write(" "); // fmt:param org.apache.taglibs.standard.tag.rt.fmt.ParamTag _jspx_th_fmt_005fparam_005f1 = (org.apache.taglibs.standard.tag.rt.fmt.ParamTag) _005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody.get( org.apache.taglibs.standard.tag.rt.fmt.ParamTag.class); _jspx_th_fmt_005fparam_005f1.setPageContext(_jspx_page_context); _jspx_th_fmt_005fparam_005f1.setParent( (javax.servlet.jsp.tagext.Tag) _jspx_th_fmt_005fmessage_005f1); // /admin/index.jsp(59,16) name = value type = null reqTime = true required = false // fragment = false deferredValue = false expectedTypeName = null deferredMethod = // false methodSignature = null _jspx_th_fmt_005fparam_005f1.setValue(serverName); int _jspx_eval_fmt_005fparam_005f1 = _jspx_th_fmt_005fparam_005f1.doStartTag(); if (_jspx_th_fmt_005fparam_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody.reuse( _jspx_th_fmt_005fparam_005f1); return; } _005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody.reuse( _jspx_th_fmt_005fparam_005f1); out.write("\n"); out.write(" "); int evalDoAfterBody = _jspx_th_fmt_005fmessage_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); if (_jspx_eval_fmt_005fmessage_005f1 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.popBody(); } } if (_jspx_th_fmt_005fmessage_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey.reuse( _jspx_th_fmt_005fmessage_005f1); return; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey.reuse( _jspx_th_fmt_005fmessage_005f1); out.write("\n"); out.write(" </p>\n"); out.write("\n"); out.write(" <p> </p>\n"); out.write("\n"); out.write(" <div id=\"workArea\">\n"); out.write(" <div id=\"systemInfoDiv\">\n"); out.write(" "); if (loggedIn && passwordExpires != null) { out.write("\n"); out.write(" <div class=\"info-box\"><p>Your password expires at "); out.print(passwordExpires); out.write( ". Please change by visiting <a href=\"../user/change-passwd.jsp?isUserChange=true&returnPath=../admin/index.jsp\">here</a></p></div>\n"); out.write(" "); } if (loggedIn && serverAdminComponentFound) { out.write("\n"); out.write(" <div id=\"result\"></div>\n"); out.write(" <script type=\"text/javascript\">\n"); out.write(" jQuery.noConflict();\n"); out.write(" var refresh;\n"); out.write(" function refreshStats() {\n"); out.write( " var url = \"../server-admin/system_status_ajaxprocessor.jsp\";\n"); out.write(" var data = null;\n"); out.write(" try {\n"); out.write(" jQuery.ajax({\n"); out.write(" url: \"../admin/jsp/session-validate.jsp\",\n"); out.write(" type: \"GET\",\n"); out.write(" dataType: \"html\",\n"); out.write(" data: data,\n"); out.write(" complete: function(res, status){\n"); out.write( " if (res.responseText.search(/----valid----/) != -1) {\n"); out.write( " jQuery(\"#result\").load(url, null, function (responseText, status, XMLHttpRequest) {\n"); out.write(" if (status != \"success\") {\n"); out.write(" stopRefreshStats();\n"); out.write(" }\n"); out.write(" });\n"); out.write(" } else {\n"); out.write(" stopRefreshStats();\n"); out.write(" }\n"); out.write(" },error: function(res, status, error){\n"); out.write(" \tstopRefreshStats();\n"); out.write(" }\n"); out.write(" });\n"); out.write(" } catch (e) {\n"); out.write(" \tstopRefreshStats();\n"); out.write(" }\n"); out.write(" }\n"); out.write(" function stopRefreshStats() {\n"); out.write(" if (refresh) {\n"); out.write(" clearInterval(refresh);\n"); out.write(" }\n"); out.write(" }\n"); out.write(" try {\n"); out.write(" jQuery(document).ready(function() {\n"); out.write(" refreshStats();\n"); out.write( " if (document.getElementById('systemInfoDiv').style.display == '') {\n"); out.write( " refresh = setInterval(\"refreshStats()\", 6000);\n"); out.write(" }\n"); out.write(" });\n"); out.write(" } catch (e) {\n"); out.write(" } // ignored\n"); out.write(" </script>\n"); out.write(" "); } out.write("\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); int evalDoAfterBody = _jspx_th_fmt_005fbundle_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); if (_jspx_eval_fmt_005fbundle_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.popBody(); } } if (_jspx_th_fmt_005fbundle_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fbundle_0026_005fbasename.reuse( _jspx_th_fmt_005fbundle_005f0); return; } _005fjspx_005ftagPool_005ffmt_005fbundle_0026_005fbasename.reuse( _jspx_th_fmt_005fbundle_005f0); out.write('\n'); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) { } if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
private void sendToFrameworkForLogout( HttpServletRequest request, HttpServletResponse response, SAMLSSOReqValidationResponseDTO signInRespDTO, String relayState, String sessionId, boolean invalid, boolean isPost) throws ServletException, IOException { SAMLSSOSessionDTO sessionDTO = new SAMLSSOSessionDTO(); sessionDTO.setHttpQueryString(request.getQueryString()); sessionDTO.setRelayState(relayState); sessionDTO.setSessionId(sessionId); sessionDTO.setLogoutReq(true); sessionDTO.setInvalidLogout(invalid); if (signInRespDTO != null) { sessionDTO.setDestination(signInRespDTO.getDestination()); sessionDTO.setRequestMessageString(signInRespDTO.getRequestMessageString()); sessionDTO.setIssuer(signInRespDTO.getIssuer()); sessionDTO.setRequestID(signInRespDTO.getId()); sessionDTO.setSubject(signInRespDTO.getSubject()); sessionDTO.setRelyingPartySessionId(signInRespDTO.getRpSessionId()); sessionDTO.setAssertionConsumerURL(signInRespDTO.getAssertionConsumerURL()); sessionDTO.setValidationRespDTO(signInRespDTO); } String sessionDataKey = UUIDGenerator.generateUUID(); addSessionDataToCache( sessionDataKey, sessionDTO, IdPManagementUtil.getIdleSessionTimeOut( CarbonContext.getThreadLocalCarbonContext().getTenantDomain())); String commonAuthURL = CarbonUIUtil.getAdminConsoleURL(request); commonAuthURL = commonAuthURL.replace("samlsso/carbon/", "commonauth"); String selfPath = URLEncoder.encode("/samlsso", "UTF-8"); // Add all parameters to authentication context before sending to authentication // framework AuthenticationRequest authenticationRequest = new AuthenticationRequest(); authenticationRequest.addRequestQueryParam( FrameworkConstants.RequestParams.LOGOUT, new String[] {"true"}); authenticationRequest.setRequestQueryParams(request.getParameterMap()); authenticationRequest.setCommonAuthCallerPath(selfPath); authenticationRequest.setPost(isPost); if (signInRespDTO != null) { authenticationRequest.setRelyingParty(signInRespDTO.getIssuer()); } authenticationRequest.appendRequestQueryParams(request.getParameterMap()); // Add headers to AuthenticationRequestContext for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) { String headerName = e.nextElement().toString(); authenticationRequest.addHeader(headerName, request.getHeader(headerName)); } AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry(authenticationRequest); FrameworkUtils.addAuthenticationRequestToCache( sessionDataKey, authRequest, IdPManagementUtil.getIdleSessionTimeOut( CarbonContext.getThreadLocalCarbonContext().getTenantDomain())); String queryParams = "?" + SAMLSSOConstants.SESSION_DATA_KEY + "=" + sessionDataKey + "&" + "type" + "=" + "samlsso"; response.sendRedirect(commonAuthURL + queryParams); }
/** * Sends the user for authentication to the login page * * @param req * @param resp * @param signInRespDTO * @param relayState * @throws ServletException * @throws IOException */ private void sendToFrameworkForAuthentication( HttpServletRequest req, HttpServletResponse resp, SAMLSSOReqValidationResponseDTO signInRespDTO, String relayState, boolean isPost) throws ServletException, IOException, UserStoreException, IdentityException { SAMLSSOSessionDTO sessionDTO = new SAMLSSOSessionDTO(); sessionDTO.setHttpQueryString(req.getQueryString()); sessionDTO.setDestination(signInRespDTO.getDestination()); sessionDTO.setRelayState(relayState); sessionDTO.setRequestMessageString(signInRespDTO.getRequestMessageString()); sessionDTO.setIssuer(signInRespDTO.getIssuer()); sessionDTO.setRequestID(signInRespDTO.getId()); sessionDTO.setSubject(signInRespDTO.getSubject()); sessionDTO.setRelyingPartySessionId(signInRespDTO.getRpSessionId()); sessionDTO.setAssertionConsumerURL(signInRespDTO.getAssertionConsumerURL()); sessionDTO.setTenantDomain(SAMLSSOUtil.getTenantDomainFromThreadLocal()); if (sessionDTO.getTenantDomain() == null) { String[] splitIssuer = sessionDTO.getIssuer().split("@"); if (splitIssuer != null && splitIssuer.length == 2 && !splitIssuer[0].trim().isEmpty() && !splitIssuer[1].trim().isEmpty()) { sessionDTO.setTenantDomain(splitIssuer[1]); } else { sessionDTO.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); } } SAMLSSOUtil.setTenantDomainInThreadLocal(sessionDTO.getTenantDomain()); sessionDTO.setForceAuth(signInRespDTO.isForceAuthn()); sessionDTO.setPassiveAuth(signInRespDTO.isPassive()); sessionDTO.setValidationRespDTO(signInRespDTO); sessionDTO.setIdPInitSSO(signInRespDTO.isIdPInitSSO()); String sessionDataKey = UUIDGenerator.generateUUID(); addSessionDataToCache( sessionDataKey, sessionDTO, IdPManagementUtil.getIdleSessionTimeOut(sessionDTO.getTenantDomain())); String commonAuthURL = CarbonUIUtil.getAdminConsoleURL(req); commonAuthURL = commonAuthURL.replace( FrameworkConstants.RequestType.CLAIM_TYPE_SAML_SSO + "/" + FrameworkConstants.CARBON + "/", FrameworkConstants.COMMONAUTH); String selfPath = URLEncoder.encode("/" + FrameworkConstants.RequestType.CLAIM_TYPE_SAML_SSO, "UTF-8"); // Setting authentication request context AuthenticationRequest authenticationRequest = new AuthenticationRequest(); // Adding query parameters authenticationRequest.appendRequestQueryParams(req.getParameterMap()); for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements(); ) { String headerName = headerNames.nextElement().toString(); authenticationRequest.addHeader(headerName, req.getHeader(headerName)); } authenticationRequest.setRelyingParty(signInRespDTO.getIssuer()); authenticationRequest.setCommonAuthCallerPath(selfPath); authenticationRequest.setForceAuth(signInRespDTO.isForceAuthn()); if (!authenticationRequest.getForceAuth() && authenticationRequest.getRequestQueryParam("forceAuth") != null) { String[] forceAuth = authenticationRequest.getRequestQueryParam("forceAuth"); if (!forceAuth[0].trim().isEmpty() && Boolean.parseBoolean(forceAuth[0].trim())) { authenticationRequest.setForceAuth(Boolean.parseBoolean(forceAuth[0].trim())); } } authenticationRequest.setPassiveAuth(signInRespDTO.isPassive()); authenticationRequest.setTenantDomain(sessionDTO.getTenantDomain()); authenticationRequest.setPost(isPost); // Creating cache entry and adding entry to the cache before calling to commonauth AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry(authenticationRequest); FrameworkUtils.addAuthenticationRequestToCache( sessionDataKey, authRequest, IdPManagementUtil.getIdleSessionTimeOut(sessionDTO.getTenantDomain())); StringBuilder queryStringBuilder = new StringBuilder(); queryStringBuilder .append(commonAuthURL) .append("?") .append(SAMLSSOConstants.SESSION_DATA_KEY) .append("=") .append(sessionDataKey) .append("&") .append(FrameworkConstants.RequestParams.TYPE) .append("=") .append(FrameworkConstants.RequestType.CLAIM_TYPE_SAML_SSO); FrameworkUtils.setRequestPathCredentials(req); resp.sendRedirect(queryStringBuilder.toString()); }
private void handleIdPInitSSO( HttpServletRequest req, HttpServletResponse resp, String relayState, String queryString, String authMode, String sessionId, boolean isPost, boolean isLogout) throws UserStoreException, IdentityException, IOException, ServletException { String rpSessionId = CharacterEncoder.getSafeText(req.getParameter(MultitenantConstants.SSO_AUTH_SESSION_ID)); SAMLSSOService samlSSOService = new SAMLSSOService(); SAMLSSOReqValidationResponseDTO signInRespDTO = samlSSOService.validateIdPInitSSORequest( relayState, queryString, getQueryParams(req), CarbonUIUtil.getAdminConsoleURL(req), sessionId, rpSessionId, authMode, isLogout); if (!signInRespDTO.isLogOutReq()) { if (signInRespDTO.isValid()) { sendToFrameworkForAuthentication(req, resp, signInRespDTO, relayState, false); } else { if (log.isDebugEnabled()) { log.debug("Invalid IdP initiated SAML SSO Request"); } String errorResp = signInRespDTO.getResponse(); sendNotification( errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS, SAMLSSOConstants.Notification.EXCEPTION_MESSAGE, signInRespDTO.getAssertionConsumerURL(), req, resp); } } else { if (signInRespDTO.isValid()) { sendToFrameworkForLogout(req, resp, signInRespDTO, relayState, sessionId, false, isPost); } else { if (log.isDebugEnabled()) { log.debug("Invalid IdP initiated SAML Single Logout Request"); } if (signInRespDTO.isLogoutFromAuthFramework()) { sendToFrameworkForLogout(req, resp, null, null, sessionId, true, isPost); } else { String errorResp = signInRespDTO.getResponse(); sendNotification( errorResp, SAMLSSOConstants.Notification.INVALID_MESSAGE_STATUS, SAMLSSOConstants.Notification.EXCEPTION_MESSAGE, signInRespDTO.getAssertionConsumerURL(), req, resp); } } } }
/** * All requests are handled by this handleRequest method. In case of SAMLRequest the user will be * redirected to commonAuth servlet for authentication. Based on successful authentication of the * user a SAMLResponse is sent back to service provider. In case of logout requests, the IDP will * send logout requests to the other session participants and then send the logout response back * to the initiator. * * @param req * @param resp * @throws ServletException * @throws IOException */ private void handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost) throws ServletException, IOException { String sessionId = null; Cookie ssoTokenIdCookie = getTokenIdCookie(req); if (ssoTokenIdCookie != null) { sessionId = ssoTokenIdCookie.getValue(); } String queryString = req.getQueryString(); if (log.isDebugEnabled()) { log.debug("Query string : " + queryString); } // if an openid authentication or password authentication String authMode = CharacterEncoder.getSafeText(req.getParameter("authMode")); if (!SAMLSSOConstants.AuthnModes.OPENID.equals(authMode)) { authMode = SAMLSSOConstants.AuthnModes.USERNAME_PASSWORD; } String relayState = CharacterEncoder.getSafeText(req.getParameter(SAMLSSOConstants.RELAY_STATE)); String spEntityID = CharacterEncoder.getSafeText( req.getParameter(SAMLSSOConstants.QueryParameter.SP_ENTITY_ID.toString())); String samlRequest = CharacterEncoder.getSafeText(req.getParameter("SAMLRequest")); String sessionDataKey = CharacterEncoder.getSafeText(req.getParameter("sessionDataKey")); String slo = CharacterEncoder.getSafeText( req.getParameter(SAMLSSOConstants.QueryParameter.SLO.toString())); boolean isExpFired = false; try { String tenantDomain = CharacterEncoder.getSafeText(req.getParameter("tenantDomain")); SAMLSSOUtil.setTenantDomainInThreadLocal(tenantDomain); if (sessionDataKey != null) { // Response from common authentication framework. SAMLSSOSessionDTO sessionDTO = getSessionDataFromCache(sessionDataKey); if (sessionDTO != null) { SAMLSSOUtil.setTenantDomainInThreadLocal(sessionDTO.getTenantDomain()); if (sessionDTO.isInvalidLogout()) { log.warn("Redirecting to default logout page due to an invalid logout request"); String serverUrl = CarbonUIUtil.getAdminConsoleURL(req); resp.sendRedirect( serverUrl.replace( SAMLSSOConstants.SAML_ENDPOINT, SAMLSSOConstants.DEFAULT_LOGOUT_LOCATION)); } else if (sessionDTO.isLogoutReq()) { handleLogoutResponseFromFramework(req, resp, sessionDTO); } else { handleAuthenticationReponseFromFramework(req, resp, sessionId, sessionDTO); } removeAuthenticationResultFromCache(sessionDataKey); } else { log.error("Failed to retrieve sessionDTO from the cache for key " + sessionDataKey); String errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR, SAMLSSOConstants.Notification.EXCEPTION_STATUS, null); sendNotification( errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS, SAMLSSOConstants.Notification.EXCEPTION_MESSAGE, null, req, resp); return; } } else if (spEntityID != null || slo != null) { // idp initiated SSO/SLO handleIdPInitSSO( req, resp, relayState, queryString, authMode, sessionId, isPost, (slo != null)); } else if (samlRequest != null) { // SAMLRequest received. SP initiated SSO handleSPInitSSO( req, resp, queryString, relayState, authMode, samlRequest, sessionId, isPost); } else { log.debug("Invalid request message or single logout message "); if (sessionId == null) { String errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "Invalid request message", null); sendNotification( errorResp, SAMLSSOConstants.Notification.INVALID_MESSAGE_STATUS, SAMLSSOConstants.Notification.INVALID_MESSAGE_MESSAGE, null, req, resp); } else { // Non-SAML request are assumed to be logout requests sendToFrameworkForLogout(req, resp, null, null, sessionId, true, false); } } } catch (UserStoreException e) { if (log.isDebugEnabled()) { log.debug("Error occurred while handling SAML2 SSO request", e); } String errorResp = null; try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR, "Error occurred while handling SAML2 SSO request", null); } catch (IdentityException e1) { log.error("Error while building SAML response", e1); } sendNotification( errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS, SAMLSSOConstants.Notification.EXCEPTION_MESSAGE, null, req, resp); } catch (IdentityException e) { log.error("Error when processing the authentication request!", e); String errorResp = null; try { errorResp = SAMLSSOUtil.buildErrorResponse( SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR, "Error when processing the authentication request", null); } catch (IdentityException e1) { log.error("Error while building SAML response", e1); } sendNotification( errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS, SAMLSSOConstants.Notification.EXCEPTION_MESSAGE, null, req, resp); } }
public static String decorateVersionElement( String version, String basicVersionElement, String path, String type, String append, String screenWidth, ServletConfig config, HttpSession session, HttpServletRequest request) { String hrefPrefix = "../resources/resource.jsp?region=region3&item=resource_browser_menu&path="; String hrefPostfix = (screenWidth != null) ? "&screenWidth=" + screenWidth : ""; String patchPath = RegistryUtils.getParentPath(path); String minorPath = RegistryUtils.getParentPath(patchPath); String majorPath = RegistryUtils.getParentPath(minorPath); String servicePath = RegistryUtils.getParentPath(majorPath); String versions[] = version.split("[.]"); StringBuffer sb = new StringBuffer("$1type=\"hidden\"$2"); if (type.equals("collection")) { sb.append("<a href=\"") .append(hrefPrefix) .append(majorPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("\">") .append(versions[0]) .append("</a>"); sb.append("."); sb.append("<a href=\"") .append(hrefPrefix) .append(minorPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("\">") .append(versions[1]) .append("</a>"); sb.append("."); sb.append("<a href=\"") .append(hrefPrefix) .append(patchPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("\">") .append(versions[2]) .append("</a>"); sb.append(append); } else if (type.equals("patch")) { sb.append("<a href=\"") .append(hrefPrefix) .append(majorPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("\">") .append(versions[0]) .append("</a>"); sb.append("."); sb.append("<a href=\"") .append(hrefPrefix) .append(minorPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("\">") .append(versions[1]) .append("</a>"); sb.append("."); sb.append("<a href=\"javascript:void(0)\">").append(versions[2]).append("</a>"); sb.append(append); try { int[] adjacentVersions = getAdjacentVersions(config, session, minorPath, Integer.parseInt(versions[2])); sb.append(" "); if (adjacentVersions[0] > -1) { sb.append("<a class=\"icon-link\" style=\"background-image: ") .append("url(../resources/images/arrow-up.gif);float:none !important;") .append("margin-bottom:0px !important;margin-top:0px !important;") .append("margin-left:0px !important\" href=\"") .append(hrefPrefix) .append(minorPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("/") .append(adjacentVersions[0]) .append("\" title=\"") .append( CarbonUIUtil.geti18nString( "previous.version", "org.wso2.carbon.governance.generic.ui.i18n.Resources", request.getLocale())) .append(": ") .append(versions[0]) .append(".") .append(versions[1]) .append(".") .append(adjacentVersions[0]) .append("\"/>"); } if (adjacentVersions[1] > -1) { sb.append("<a class=\"icon-link\" style=\"background-image: ") .append("url(../resources/images/arrow-right.gif);float:none !important;") .append("margin-bottom:0px !important;margin-top:0px !important;") .append("margin-left:0px !important\" href=\"") .append(hrefPrefix) .append(minorPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("/") .append(adjacentVersions[1]) .append("\" title=\"") .append( CarbonUIUtil.geti18nString( "next.version", "org.wso2.carbon.governance.generic.ui.i18n.Resources", request.getLocale())) .append(": ") .append(versions[0]) .append(".") .append(versions[1]) .append(".") .append(adjacentVersions[1]) .append("\"/>"); } } catch (Exception ignore) { } } else if (type.equals("minor")) { sb.append("<a href=\"") .append(hrefPrefix) .append(majorPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("\">") .append(versions[0]) .append("</a>"); sb.append("."); sb.append("<a href=\"javascript:void(0)\">").append(versions[1]).append("</a>"); sb.append("."); sb.append("<a href=\"") .append(hrefPrefix) .append(patchPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("\">") .append(versions[2]) .append("</a>"); sb.append(append); try { int[] adjacentVersions = getAdjacentVersions(config, session, majorPath, Integer.parseInt(versions[1])); sb.append(" "); if (adjacentVersions[0] > -1) { String latestPatch = getGreatestChildVersion(config, session, majorPath + "/" + adjacentVersions[0]); sb.append("<a class=\"icon-link\" style=\"background-image: ") .append("url(../resources/images/arrow-up.gif);float:none !important;") .append("margin-bottom:0px !important;margin-top:0px !important;") .append("margin-left:0px !important\" href=\"") .append(hrefPrefix) .append(majorPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("/") .append(adjacentVersions[0]) .append("\" title=\"") .append( CarbonUIUtil.geti18nString( "previous.version", "org.wso2.carbon.governance.generic.ui.i18n.Resources", request.getLocale())) .append(": ") .append(versions[0]) .append(".") .append(adjacentVersions[0]) .append(".") .append(latestPatch) .append("\"/>"); } if (adjacentVersions[1] > -1) { String latestPatch = getGreatestChildVersion(config, session, majorPath + "/" + adjacentVersions[1]); sb.append("<a class=\"icon-link\" style=\"background-image: ") .append("url(../resources/images/arrow-right.gif);float:none !important;") .append("margin-bottom:0px !important;margin-top:0px !important;") .append("margin-left:0px !important\" href=\"") .append(hrefPrefix) .append(majorPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("/") .append(adjacentVersions[1]) .append("\" title=\"") .append( CarbonUIUtil.geti18nString( "next.version", "org.wso2.carbon.governance.generic.ui.i18n.Resources", request.getLocale())) .append(": ") .append(versions[0]) .append(".") .append(adjacentVersions[1]) .append(".") .append(latestPatch) .append("\"/>"); } } catch (Exception ignore) { } } else if (type.equals("major")) { sb.append("<a href=\"javascript:void(0)\">").append(versions[0]).append("</a>"); sb.append("."); sb.append("<a href=\"") .append(hrefPrefix) .append(minorPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("\">") .append(versions[1]) .append("</a>"); sb.append("."); sb.append("<a href=\"") .append(hrefPrefix) .append(patchPath.replaceAll("&", "%26")) .append(hrefPostfix) .append("\">") .append(versions[2]) .append("</a>"); sb.append(append); try { int[] adjacentVersions = getAdjacentVersions(config, session, servicePath, Integer.parseInt(versions[0])); sb.append(" "); if (adjacentVersions[0] > -1) { String latestMinor = getGreatestChildVersion(config, session, servicePath + "/" + adjacentVersions[0]); String latestPatch = getGreatestChildVersion( config, session, servicePath + "/" + adjacentVersions[0] + "/" + latestMinor); sb.append("<a class=\"icon-link\" style=\"background-image: ") .append("url(../resources/images/arrow-up.gif);float:none !important;") .append("margin-bottom:0px !important;margin-top:0px !important;") .append("margin-left:0px !important\" href=\"") .append(hrefPrefix) .append(servicePath.replaceAll("&", "%26")) .append(hrefPostfix) .append("/") .append(adjacentVersions[0]) .append("\" title=\"") .append( CarbonUIUtil.geti18nString( "previous.version", "org.wso2.carbon.governance.generic.ui.i18n.Resources", request.getLocale())) .append(": ") .append(adjacentVersions[0]) .append(".") .append(latestMinor) .append(".") .append(latestPatch) .append("\"/>"); } if (adjacentVersions[1] > -1) { String latestMinor = getGreatestChildVersion(config, session, servicePath + "/" + adjacentVersions[1]); String latestPatch = getGreatestChildVersion( config, session, servicePath + "/" + adjacentVersions[1] + "/" + latestMinor); sb.append("<a class=\"icon-link\" style=\"background-image: ") .append("url(../resources/images/arrow-right.gif);float:none !important;") .append("margin-bottom:0px !important;margin-top:0px !important;") .append("margin-left:0px !important\" href=\"") .append(hrefPrefix) .append(servicePath.replaceAll("&", "%26")) .append(hrefPostfix) .append("/") .append(adjacentVersions[1]) .append("\" title=\"") .append( CarbonUIUtil.geti18nString( "next.version", "org.wso2.carbon.governance.generic.ui.i18n.Resources", request.getLocale())) .append(": ") .append(adjacentVersions[1]) .append(".") .append(latestMinor) .append(".") .append(latestPatch) .append("\"/>"); } } catch (Exception ignore) { } } return basicVersionElement.replaceAll( "(<input[^>]*)type=\"text\"([^>]*id=\"id_Overview_Version\"[^>]*>)", sb.toString()); }
public static void buildMenuItems(HttpServletRequest request, String s, String s1, String s2) { int menuOrder = 50; if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/resources/ws-api")) { HttpSession session = request.getSession(); String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); try { WSRegistryServiceClient registry = new WSRegistryServiceClient(s2, cookie); List<GovernanceArtifactConfiguration> configurations = GovernanceUtils.findGovernanceArtifactConfigurations(registry); Map<String, String> customAddUIMap = new LinkedHashMap<String, String>(); Map<String, String> customViewUIMap = new LinkedHashMap<String, String>(); List<Menu> userCustomMenuItemsList = new LinkedList<Menu>(); for (GovernanceArtifactConfiguration configuration : configurations) { Component component = new Component(); OMElement uiConfigurations = configuration.getUIConfigurations(); String key = configuration.getKey(); String configurationPath = RegistryConstants.CONFIG_REGISTRY_BASE_PATH + RegistryConstants.GOVERNANCE_COMPONENT_PATH + "/configuration/"; String layoutStoragePath = configurationPath + key; RealmService realmService = registry.getRegistryContext().getRealmService(); if (realmService .getTenantUserRealm(realmService.getTenantManager().getTenantId(s1)) .getAuthorizationManager() .isUserAuthorized(s, configurationPath, ActionConstants.PUT) || registry.resourceExists(layoutStoragePath)) { List<Menu> menuList = component.getMenusList(); if (uiConfigurations != null) { ComponentBuilder.processMenus("artifactType", uiConfigurations, component); ComponentBuilder.processCustomUIs(uiConfigurations, component); } if (menuList.size() == 0) { // if no menu definitions were present, define the default ones. menuOrder = buildMenuList(request, configuration, menuList, key, menuOrder); } userCustomMenuItemsList.addAll(menuList); customAddUIMap.putAll(component.getCustomAddUIMap()); Map<String, String> viewUIMap = component.getCustomViewUIMap(); if (viewUIMap.isEmpty()) { // if no custom UI definitions were present, define the default. buildViewUI(configuration, viewUIMap, key); } customViewUIMap.putAll(viewUIMap); OMElement layout = configuration.getContentDefinition(); if (layout != null && !registry.resourceExists(layoutStoragePath)) { Resource resource = registry.newResource(); resource.setContent(RegistryUtils.encodeString(layout.toString())); resource.setMediaType("application/xml"); registry.put(layoutStoragePath, resource); } } } session.setAttribute( MenuAdminClient.USER_CUSTOM_MENU_ITEMS, userCustomMenuItemsList.toArray(new Menu[userCustomMenuItemsList.size()])); session.setAttribute("customAddUI", customAddUIMap); session.setAttribute("customViewUI", customViewUIMap); } catch (RegistryException e) { log.error("unable to create connection to registry"); } catch (org.wso2.carbon.user.api.UserStoreException e) { log.error("unable to realm service"); } } }
private static int buildMenuList( HttpServletRequest request, GovernanceArtifactConfiguration configuration, List<Menu> menuList, String key, int menuOrder) { String singularLabel = configuration.getSingularLabel(); String pluralLabel = configuration.getPluralLabel(); boolean hasNamespace = configuration.hasNamespace(); String lifecycleAttribute = key + "Lifecycle_lifecycleName"; lifecycleAttribute = BuilLifecycleAttribute( configuration, DEFAULT_LIFECYCLE_GENERATOR_CLASS, lifecycleAttribute); if (singularLabel == null || pluralLabel == null) { log.error( "The singular label and plural label have not " + "been defined for the artifact type: " + key); } else { int iconSet = configuration.getIconSet(); if (CarbonUIUtil.isUserAuthorized( request, "/permission/admin/manage/resources/govern/" + key + "/add") && CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/resources/browse") && CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/resources/ws-api")) { Menu addMenu = new Menu(); addMenu.setId("governance_add_" + key + "_menu"); addMenu.setI18nKey(singularLabel); addMenu.setParentMenu("add_sub_menu"); if (configuration.getExtension() == null) { addMenu.setLink("../generic/add_edit.jsp"); addMenu.setUrlParameters( "key=" + key + "&lifecycleAttribute=" + lifecycleAttribute + "&breadcrumb=" + singularLabel); } else { addMenu.setLink("../generic/add_content.jsp"); addMenu.setUrlParameters( "key=" + key + "&lifecycleAttribute=" + lifecycleAttribute + "&breadcrumb=" + singularLabel + "&mediaType=" + configuration.getMediaType() + "&extension=" + configuration.getExtension() + "&singularLabel=" + singularLabel + "&pluralLabel=" + pluralLabel + "&hasNamespace" + hasNamespace); } addMenu.setRegion("region3"); addMenu.setOrder(String.valueOf(menuOrder)); addMenu.setStyleClass("manage"); if (iconSet > 0) { addMenu.setIcon("../generic/images/add" + iconSet + ".png"); } else { addMenu.setIcon("../images/add.gif"); } addMenu.setAllPermissionsRequired(true); addMenu.setRequirePermission( new String[] { "/permission/admin/manage/resources/govern/" + key + "/add", "/permission/admin/manage/resources/browse", "/permission/admin/manage/resources/ws-api" }); menuList.add(addMenu); } if (CarbonUIUtil.isUserAuthorized( request, "/permission/admin/manage/resources/govern/" + key + "/list") && CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/resources/ws-api")) { Menu listMenu = new Menu(); listMenu.setId("governance_list_" + key + "_menu"); listMenu.setI18nKey(pluralLabel); listMenu.setParentMenu("list_sub_menu"); if (configuration.getExtension() == null) { listMenu.setLink("../generic/list.jsp"); listMenu.setUrlParameters( "key=" + key + "&breadcrumb=" + pluralLabel + "&singularLabel=" + singularLabel + "&pluralLabel=" + pluralLabel); } else { listMenu.setLink("../generic/list_content.jsp"); listMenu.setUrlParameters( "key=" + key + "&lifecycleAttribute=" + lifecycleAttribute + "&breadcrumb=" + singularLabel + "&mediaType=" + configuration.getMediaType() + "&singularLabel=" + singularLabel + "&pluralLabel=" + pluralLabel + "&hasNamespace=" + hasNamespace); } listMenu.setRegion("region3"); listMenu.setOrder(String.valueOf(menuOrder)); listMenu.setStyleClass("manage"); if (iconSet > 0) { listMenu.setIcon("../generic/images/list" + iconSet + ".png"); } else { listMenu.setIcon("../images/list.gif"); } listMenu.setAllPermissionsRequired(true); listMenu.setRequirePermission( new String[] { "/permission/admin/manage/resources/govern/" + key + "/list", "/permission/admin/manage/resources/ws-api" }); menuList.add(listMenu); } /*if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/configure/governance/" + key + "-ui")) { Menu configureMenu = new Menu(); configureMenu.setId("governance_" + key + "_config_menu"); configureMenu.setI18nKey(pluralLabel); configureMenu.setParentMenu("configure_menu"); configureMenu.setLink("../generic/configure.jsp"); configureMenu.setUrlParameters("key=" + key + "&breadcrumb=" + pluralLabel + "&add_edit_region=region3&add_edit_item=governance_add_" + key + "_menu" + "&lifecycleAttribute=" + lifecycleAttribute + "&add_edit_breadcrumb=" + singularLabel + "&singularLabel=" + singularLabel + "&pluralLabel=" + pluralLabel); configureMenu.setRegion("region1"); configureMenu.setOrder("40"); configureMenu.setStyleClass("manage"); if (iconSet > 0) { configureMenu.setIcon("../generic/images/configure" + iconSet + ".png"); } else { configureMenu.setIcon("../generic/images/services1.gif"); } configureMenu.setRequirePermission( new String[]{"/permission/admin/configure/governance/" + key + "-ui"}); menuList.add(configureMenu); }*/ menuOrder++; } return menuOrder; }