List of usage examples for javax.servlet ServletContext getAttribute
public Object getAttribute(String name);
null
if there is no attribute by that name. From source file:org.apache.hadoop.hdfs.server.namenode.ImageServlet.java
@Override public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { try {/*w ww .jav a 2s . c o m*/ final ServletContext context = getServletContext(); final FSImage nnImage = NameNodeHttpServer.getFsImageFromContext(context); final GetImageParams parsedParams = new GetImageParams(request, response); final Configuration conf = (Configuration) context.getAttribute(JspHelper.CURRENT_CONF); final NameNodeMetrics metrics = NameNode.getNameNodeMetrics(); validateRequest(context, conf, request, response, nnImage, parsedParams.getStorageInfoString()); UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { if (parsedParams.isGetImage()) { long txid = parsedParams.getTxId(); File imageFile = null; String errorMessage = "Could not find image"; if (parsedParams.shouldFetchLatest()) { imageFile = nnImage.getStorage().getHighestFsImageName(); } else { errorMessage += " with txid " + txid; imageFile = nnImage.getStorage().getFsImage(txid, EnumSet.of(NameNodeFile.IMAGE, NameNodeFile.IMAGE_ROLLBACK)); } if (imageFile == null) { throw new IOException(errorMessage); } CheckpointFaultInjector.getInstance().beforeGetImageSetsHeaders(); long start = monotonicNow(); serveFile(imageFile); if (metrics != null) { // Metrics non-null only when used inside name node long elapsed = monotonicNow() - start; metrics.addGetImage(elapsed); } } else if (parsedParams.isGetEdit()) { long startTxId = parsedParams.getStartTxId(); long endTxId = parsedParams.getEndTxId(); File editFile = nnImage.getStorage().findFinalizedEditsFile(startTxId, endTxId); long start = monotonicNow(); serveFile(editFile); if (metrics != null) { // Metrics non-null only when used inside name node long elapsed = monotonicNow() - start; metrics.addGetEdit(elapsed); } } return null; } private void serveFile(File file) throws IOException { FileInputStream fis = new FileInputStream(file); try { setVerificationHeadersForGet(response, file); setFileNameHeaders(response, file); if (!file.exists()) { // Potential race where the file was deleted while we were in the // process of setting headers! throw new FileNotFoundException(file.toString()); // It's possible the file could be deleted after this point, but // we've already opened the 'fis' stream. // It's also possible length could change, but this would be // detected by the client side as an inaccurate length header. } // send file TransferFsImage.copyFileToStream(response.getOutputStream(), file, fis, getThrottler(conf)); } finally { IOUtils.closeStream(fis); } } }); } catch (Throwable t) { String errMsg = "GetImage failed. " + StringUtils.stringifyException(t); response.sendError(HttpServletResponse.SC_GONE, errMsg); throw new IOException(errMsg); } finally { response.getOutputStream().close(); } }
From source file:org.carrot2.webapp.QueryProcessorServlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); final ServletContext servletContext = config.getServletContext(); /*/*w w w . ja va2 s. c o m*/ * If initialized, custom logging initializer will be here. Save its reference for * deferred initialization (for servlet APIs < 2.5). */ logInitializer = (LogInitContextListener) servletContext.getAttribute(LogInitContextListener.CONTEXT_ID); /* * Initialize global configuration and publish it. */ this.webappConfig = WebappConfig.getSingleton(servletContext); this.unknownToDefaultTransformer = new UnknownToDefaultTransformer(webappConfig, false); this.unknownToDefaultTransformerWithMaxResults = new UnknownToDefaultTransformer(webappConfig, true); /* * Initialize the controller. */ List<IResourceLocator> locators = Lists.newArrayList(); locators.add( new PrefixDecoratorLocator(new ServletContextLocator(getServletContext()), "/WEB-INF/resources/")); if (Boolean.getBoolean(ENABLE_CLASSPATH_LOCATOR)) locators.add(Location.CONTEXT_CLASS_LOADER.locator); controller = ControllerFactory.createCachingPooling(ResultsCacheModel.toClassArray(webappConfig.caches)); controller.init(ImmutableMap.<String, Object>of( AttributeUtils.getKey(DefaultLexicalDataFactory.class, "resourceLookup"), new ResourceLookup(locators)), webappConfig.components.getComponentConfigurations()); jawrUrlGenerator = new JawrUrlGenerator(servletContext); }
From source file:org.apache.struts2.views.freemarker.FreemarkerManager.java
protected ScopesHashModel buildScopesHashModel(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, ObjectWrapper wrapper, ValueStack stack) { ScopesHashModel model = new ScopesHashModel(wrapper, servletContext, request, stack); // Create hash model wrapper for servlet context (the application) // only need one thread to do this once, per servlet context synchronized (servletContext) { ServletContextHashModel servletContextModel = (ServletContextHashModel) servletContext .getAttribute(ATTR_APPLICATION_MODEL); if (servletContextModel == null) { GenericServlet servlet = JspSupportServlet.jspSupportServlet; // TODO if the jsp support servlet isn't load-on-startup then it won't exist // if it hasn't been accessed, and a JSP page is accessed if (servlet != null) { servletContextModel = new ServletContextHashModel(servlet, wrapper); servletContext.setAttribute(ATTR_APPLICATION_MODEL, servletContextModel); TaglibFactory taglibs = new TaglibFactory(servletContext); servletContext.setAttribute(ATTR_JSP_TAGLIBS_MODEL, taglibs); }/*from w ww. j a v a 2s .com*/ } model.put(KEY_APPLICATION, servletContextModel); model.put(KEY_JSP_TAGLIBS, (TemplateModel) servletContext.getAttribute(ATTR_JSP_TAGLIBS_MODEL)); } // Create hash model wrapper for session HttpSession session = request.getSession(false); if (session != null) { model.put(KEY_SESSION_MODEL, new HttpSessionHashModel(session, wrapper)); } else { // no session means no attributes ??? // model.put(KEY_SESSION_MODEL, new SimpleHash()); } // Create hash model wrapper for the request attributes HttpRequestHashModel requestModel = (HttpRequestHashModel) request.getAttribute(ATTR_REQUEST_MODEL); if ((requestModel == null) || (requestModel.getRequest() != request)) { requestModel = new HttpRequestHashModel(request, response, wrapper); request.setAttribute(ATTR_REQUEST_MODEL, requestModel); } model.put(KEY_REQUEST_MODEL, requestModel); // Create hash model wrapper for request parameters HttpRequestParametersHashModel reqParametersModel = (HttpRequestParametersHashModel) request .getAttribute(ATTR_REQUEST_PARAMETERS_MODEL); if (reqParametersModel == null || requestModel.getRequest() != request) { reqParametersModel = new HttpRequestParametersHashModel(request); request.setAttribute(ATTR_REQUEST_PARAMETERS_MODEL, reqParametersModel); } model.put(KEY_REQUEST_PARAMETER_MODEL, reqParametersModel); return model; }
From source file:com.concursive.connect.web.controller.hooks.SecurityHook.java
/** * Checks to see if a User session object exists, if not then the security * check fails./*from w w w . j a v a 2 s . c om*/ * * @param servlet Description of the Parameter * @param request Description of the Parameter * @param response Description of the Parameter * @return Description of the Return Value */ public String beginRequest(Servlet servlet, HttpServletRequest request, HttpServletResponse response) { LOG.debug("Security request made"); ServletConfig config = servlet.getServletConfig(); ServletContext context = config.getServletContext(); // Application wide preferences ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute(Constants.APPLICATION_PREFS); // Get the intended action, if going to the login module, then let it proceed String s = request.getServletPath(); int slash = s.lastIndexOf("/"); s = s.substring(slash + 1); // If not setup then go to setup if (!s.startsWith("Setup") && !prefs.isConfigured()) { return "NotSetupError"; } // External calls if (s.startsWith("Service")) { return null; } // Set the layout relevant to this request if ("text".equals(request.getParameter("out")) || "text".equals(request.getAttribute("out"))) { // do not use a layout, send the raw output } else if ("true".equals(request.getParameter(Constants.REQUEST_PARAM_POPUP))) { request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp"); } else if ("true".equals(request.getParameter(Constants.REQUEST_PARAM_STYLE))) { request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp"); } else { request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, context.getAttribute(Constants.REQUEST_TEMPLATE)); } // If going to Setup then allow if (s.startsWith("Setup")) { request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp"); return null; } // If going to Upgrade then allow if (s.startsWith("Upgrade")) { request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp"); return null; } // Detect mobile users and mobile formatting // ClientType clientType = (ClientType) request.getSession().getAttribute(Constants.SESSION_CLIENT_TYPE); // @todo introduce when mobile is implemented // if (clientType.getMobile()) { // request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layoutMobile.jsp"); // } // URL forwarding for MVC requests (*.do, etc.) String requestedPath = (String) request.getAttribute("requestedURL"); if (requestedPath == null && "GET".equals(request.getMethod()) && request.getParameter("redirectTo") == null) { // Save the requestURI to be used downstream String contextPath = request.getContextPath(); String uri = request.getRequestURI(); String queryString = request.getQueryString(); requestedPath = uri.substring(contextPath.length()) + (queryString == null ? "" : "?" + queryString); LOG.debug("Requested path: " + requestedPath); request.setAttribute("requestedURL", requestedPath); // It's important the user is using the correct URL for accessing content; // The portal has it's own redirect scheme, this is a general catch all if (!s.startsWith("Portal") && !uri.contains(".shtml") && prefs.has(ApplicationPrefs.WEB_DOMAIN_NAME)) { // Check to see if an old domain name is used PortalBean bean = new PortalBean(request); String expectedDomainName = prefs.get(ApplicationPrefs.WEB_DOMAIN_NAME); if (expectedDomainName != null && requestedPath != null && !"127.0.0.1".equals(bean.getServerName()) && !"127.0.0.1".equals(expectedDomainName) && !"localhost".equals(bean.getServerName()) && !"localhost".equals(expectedDomainName) && !bean.getServerName().equals(expectedDomainName) && !bean.getServerName().startsWith("10.") && !bean.getServerName().startsWith("172.") && !bean.getServerName().startsWith("192.")) { if (uri != null && !uri.substring(1).equals(prefs.get("PORTAL.INDEX"))) { String newUrl = URLFactory.createURL(prefs.getPrefs()) + requestedPath; request.setAttribute("redirectTo", newUrl); LOG.debug("redirectTo: " + newUrl); request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT); return "Redirect301"; } } } } // Version check if (!s.startsWith("Login") && ApplicationVersion.isOutOfDate(prefs)) { return "UpgradeCheck"; } // Get the user object from the Session Validation... if (sessionValidator == null) { sessionValidator = SessionValidatorFactory.getInstance() .getSessionValidator(servlet.getServletConfig().getServletContext(), request); LOG.debug("Found sessionValidator? " + (sessionValidator != null)); } // Check cookie for user's previous location info SearchBean searchBean = (SearchBean) request.getSession().getAttribute(Constants.SESSION_SEARCH_BEAN); if (searchBean == null) { String searchLocation = CookieUtils.getCookieValue(request, Constants.COOKIE_USER_SEARCH_LOCATION); if (searchLocation != null) { LOG.debug("Setting search location from cookie: " + searchLocation); searchBean = new SearchBean(); searchBean.setLocation(searchLocation); request.getSession().setAttribute(Constants.SESSION_SEARCH_BEAN, searchBean); } } // Continue with session creation... User userSession = sessionValidator.validateSession(context, request, response); ConnectionElement ceSession = (ConnectionElement) request.getSession() .getAttribute(Constants.SESSION_CONNECTION_ELEMENT); // The user is going to the portal so get them guest credentials if they need them if ("true".equals(prefs.get("PORTAL")) || s.startsWith("Register") || s.startsWith("ResetPassword") || s.startsWith("LoginAccept") || s.startsWith("LoginReject") || s.startsWith("Search") || s.startsWith("ContactUs")) { if (userSession == null || ceSession == null) { // Allow portal mode to create a default session with guest capabilities userSession = UserUtils.createGuestUser(); request.getSession().setAttribute(Constants.SESSION_USER, userSession); // Give them a connection element ceSession = new ConnectionElement(); ceSession.setDriver(prefs.get("SITE.DRIVER")); ceSession.setUrl(prefs.get("SITE.URL")); ceSession.setUsername(prefs.get("SITE.USER")); ceSession.setPassword(prefs.get("SITE.PASSWORD")); request.getSession().setAttribute(Constants.SESSION_CONNECTION_ELEMENT, ceSession); } // Make sure SSL is being used for this connection if (userSession.getId() > 0 && "true".equals(prefs.get("SSL")) && !"https".equals(request.getScheme())) { LOG.info("Redirecting to..." + requestedPath); request.setAttribute("redirectTo", "https://" + request.getServerName() + request.getContextPath() + requestedPath); request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT); return "Redirect301"; } // Generate global items Connection db = null; try { db = getConnection(context, request); // TODO: Implement cache since every hit needs this list if (db != null) { // Load the project languages WebSiteLanguageList webSiteLanguageList = new WebSiteLanguageList(); webSiteLanguageList.setEnabled(Constants.TRUE); webSiteLanguageList.buildList(db); // If an admin of a language, enable it... webSiteLanguageList.add(userSession.getWebSiteLanguageList()); request.setAttribute("webSiteLanguageList", webSiteLanguageList); // Load the menu list ProjectList menu = new ProjectList(); PagedListInfo menuListInfo = new PagedListInfo(); menuListInfo.setColumnToSortBy("p.portal_default desc, p.level asc, p.title asc"); menuListInfo.setItemsPerPage(-1); menu.setPagedListInfo(menuListInfo); menu.setIncludeGuestProjects(false); menu.setPortalState(Constants.TRUE); menu.setOpenProjectsOnly(true); menu.setApprovedOnly(true); menu.setBuildLink(true); menu.setLanguageId(webSiteLanguageList.getLanguageId(request)); menu.buildList(db); request.setAttribute("menuList", menu); // Load the main profile to use throughout Project mainProfile = ProjectUtils.loadProject(prefs.get("MAIN_PROFILE")); request.setAttribute(Constants.REQUEST_MAIN_PROFILE, mainProfile); // Load the project categories for search and tab menus ProjectCategoryList categoryList = new ProjectCategoryList(); categoryList.setEnabled(Constants.TRUE); categoryList.setTopLevelOnly(true); categoryList.buildList(db); request.setAttribute(Constants.REQUEST_TAB_CATEGORY_LIST, categoryList); // Determine the tab that needs to be highlighted int chosenTabId = -1; if (requestedPath != null) { String chosenCategory = null; String chosenTab = null; if (requestedPath.length() > 0) { chosenTab = requestedPath.substring(1); } LOG.debug("chosenTab? " + chosenTab); if (chosenTab == null || "".equals(chosenTab)) { LOG.debug("Setting tab to Home"); chosenTab = "home.shtml"; } else { boolean foundChosenTab = false; for (ProjectCategory projectCategory : categoryList) { String categoryName = projectCategory.getDescription(); String normalizedCategoryTab = projectCategory.getNormalizedCategoryName() .concat(".shtml"); if (chosenTab.startsWith(normalizedCategoryTab)) { foundChosenTab = true; chosenCategory = categoryName; chosenTabId = projectCategory.getId(); LOG.debug("found: " + chosenCategory); } } if (!foundChosenTab) { LOG.debug("No tab to highlight"); chosenTab = "none"; } } request.setAttribute("chosenTab", chosenTab); request.setAttribute("chosenCategory", chosenCategory); } // Go through the tabs and remove the ones the user shouldn't see, also check permission if (!userSession.isLoggedIn()) { boolean allowed = true; Iterator i = categoryList.iterator(); while (i.hasNext()) { ProjectCategory projectCategory = (ProjectCategory) i.next(); if (projectCategory.getSensitive()) { if (chosenTabId == projectCategory.getId()) { allowed = false; } i.remove(); } } if (!allowed) { // Redirect to the login, perhaps the page would exist then String newUrl = URLFactory.createURL(prefs.getPrefs()) + "/login?redirectTo=" + requestedPath; request.setAttribute("redirectTo", newUrl); LOG.debug("redirectTo: " + newUrl); request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT); return "Redirect301"; } } // Category drop-down for search HtmlSelect thisSelect = categoryList.getHtmlSelect(); thisSelect.addItem(-1, prefs.get("TITLE"), 0); request.setAttribute(Constants.REQUEST_MENU_CATEGORY_LIST, thisSelect); } } catch (Exception e) { LOG.error("Global items error", e); } finally { this.freeConnection(context, db); } } // The user is not going to login, so verify login if (!s.startsWith("Login")) { if (userSession == null || ceSession == null) { // boot them off now LOG.debug("Security failed."); LoginBean failedSession = new LoginBean(); failedSession.addError("actionError", "* Please login, your session has expired"); failedSession.checkURL(request); request.setAttribute("LoginBean", failedSession); request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT); return "SecurityCheck"; } else { // The user should have a valid login now, so let them proceed LOG.debug("Security passed: " + userSession.getId() + " (" + userSession.getUsername() + ")"); } } // Generate user's global items if (userSession != null && userSession.getId() > 0) { Connection db = null; try { db = getConnection(context, request); // TODO: Implement cache since every hit needs this list if (db != null) { // A map for global alerts ArrayList<String> alerts = new ArrayList<String>(); request.setAttribute(Constants.REQUEST_GLOBAL_ALERTS, alerts); // Check to see if the application is configured... if (userSession.getAccessAdmin()) { String url = URLFactory.createURL(prefs.getPrefs()); if (url == null) { alerts.add( "The application configuration requires that the URL properties are updated. Store <strong>" + RequestUtils.getAbsoluteServerUrl(request) + "</strong>? <a href=\"" + RequestUtils.getAbsoluteServerUrl(request) + "/AdminUsage.do?command=StoreURL\">Save Changes</a>"); } else if (!url.equals(RequestUtils.getAbsoluteServerUrl(request))) { alerts.add("There is a configuration mismatch -- expected: <strong>" + RequestUtils.getAbsoluteServerUrl(request) + "</strong> but the configuration has <strong><a href=\"" + url + "\">" + url + "</a></strong> <a href=\"" + RequestUtils.getAbsoluteServerUrl(request) + "/AdminUsage.do?command=StoreURL\">Save Changes</a>"); } } // Check the # of invitations int invitationCount = InvitationList.queryCount(db, userSession.getId(), userSession.getProfileProjectId()); request.setAttribute(Constants.REQUEST_INVITATION_COUNT, String.valueOf(invitationCount)); // Check the # of private messages int newMailCount = PrivateMessageList.queryUnreadCountForUser(db, userSession.getId()); request.setAttribute(Constants.REQUEST_PRIVATE_MESSAGE_COUNT, String.valueOf(newMailCount)); // NOTE: removed because not currently used // Check the number of what's new // int whatsNewCount = ProjectUtils.queryWhatsNewCount(db, userSession.getId()); // request.setAttribute(Constants.REQUEST_WHATS_NEW_COUNT, String.valueOf(whatsNewCount)); // Check the number of assignments // int whatsAssignedCount = ProjectUtils.queryWhatsAssignedCount(db, userSession.getId()); // request.setAttribute(Constants.REQUEST_WHATS_ASSIGNED_COUNT, String.valueOf(whatsAssignedCount)); // int projectCount = ProjectUtils.queryMyProjectCount(db, userSession.getId()); // request.setAttribute(Constants.REQUEST_MY_PROJECT_COUNT, String.valueOf(projectCount)); } } catch (Exception e) { LOG.error("User's global items error", e); } finally { this.freeConnection(context, db); } } return null; }
From source file:com.serotonin.m2m2.Lifecycle.java
private void configureDwr(WebAppContext context) { this.LOG.debug(context + " context"); ServletContext sc = context.getServletContext(); this.LOG.debug(sc + " sc name: " + Container.class.getName()); Container container = (Container) sc.getAttribute(Container.class.getName()); CreatorManager creatorManager = (CreatorManager) container.getBean(CreatorManager.class.getName()); for (String type : ModuleRegistry.getDataSourceDefinitionTypes()) { Class clazz = ModuleRegistry.getDataSourceDefinition(type).getDwrClass(); if (clazz != null) { String js = clazz.getSimpleName(); if (creatorManager.getCreatorNames().contains(js)) { this.LOG.info("??DWR" + clazz.getName()); } else { NewCreator c = new NewCreator(); c.setClass(clazz.getName()); c.setScope("application"); c.setJavascript(js);//w w w . jav a2 s.co m creatorManager.addCreator(js, c); } } } for (String type : ModuleRegistry.getPublisherDefinitionTypes()) { Class clazz = ModuleRegistry.getPublisherDefinition(type).getDwrClass(); if (clazz != null) { String js = clazz.getSimpleName(); if (creatorManager.getCreatorNames().contains(js)) { this.LOG.info("??DWR" + clazz.getName()); } else { NewCreator c = new NewCreator(); c.setClass(clazz.getName()); c.setScope("application"); c.setJavascript(js); creatorManager.addCreator(js, c); } } } for (DwrDefinition def : ModuleRegistry.getDefinitions(DwrDefinition.class)) { Class clazz = def.getDwrClass(); if (clazz != null) { String js = clazz.getSimpleName(); if (creatorManager.getCreatorNames().contains(js)) { this.LOG.info("??DWR" + clazz.getName()); } else { ModuleDwrCreator c = new ModuleDwrCreator(def.getModule()); c.setClass(clazz.getName()); c.setScope("application"); c.setJavascript(js); creatorManager.addCreator(js, c); } } } BlabberConverterManager converterManager = (BlabberConverterManager) container .getBean(ConverterManager.class.getName()); for (DwrConversionDefinition def : ModuleRegistry.getDefinitions(DwrConversionDefinition.class)) for (DwrClassConversion conversion : def.getConversions()) try { Map params = new HashMap(); String converterType = conversion.getConverterType(); if ("bean".equals(converterType)) { String paramKey = null; List cludes = new ArrayList(); Converter converter = converterManager .getConverterAssignableFromNoAdd(conversion.getClazz()); if ((converter instanceof BlabberBeanConverter)) { converterType = "blabberBean"; BlabberBeanConverter blab = (BlabberBeanConverter) converter; if ((!org.apache.commons.collections.CollectionUtils.isEmpty(blab.getExclusions())) && (conversion.getIncludes() != null)) { throw new RuntimeException("Class conversion '" + conversion.getClazz().getName() + "' cannot have inclusions because the overriden converter has exclusions"); } if ((!org.apache.commons.collections.CollectionUtils.isEmpty(blab.getInclusions())) && (conversion.getExcludes() != null)) { throw new RuntimeException("Class conversion '" + conversion.getClazz().getName() + "' cannot have exclusions because the overriden converter has inclusions"); } if (!org.apache.commons.collections.CollectionUtils.isEmpty(blab.getInclusions())) { paramKey = "include"; cludes.addAll(blab.getInclusions()); } else if (!org.apache.commons.collections.CollectionUtils .isEmpty(blab.getExclusions())) { paramKey = "exclude"; cludes.addAll(blab.getExclusions()); } } if (conversion.getIncludes() != null) { paramKey = "include"; cludes.addAll(conversion.getIncludes()); } else if (conversion.getExcludes() != null) { paramKey = "exclude"; cludes.addAll(conversion.getExcludes()); } if (paramKey != null) { params.put(paramKey, com.serotonin.util.CollectionUtils.implode(cludes, ",")); } } converterManager.addConverter(conversion.getClazz().getName(), converterType, params); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.getobjects.servlets.WOServletAdaptor.java
protected String valueFromServletConfig(final ServletConfig _cfg, final String _key) { String an = _cfg.getInitParameter(_key); if (an != null) return an; final ServletContext sctx = _cfg.getServletContext(); if (sctx == null) return null; /*/* www . j a v a2 s .c om*/ * This is specified in web.xml like: * <context-param> * <param-name>WOAppName</param-name> * <param-value>com.zideone.HelloWorld.HelloWorld</param-value> * </context-param> */ if ((an = sctx.getInitParameter(_key)) != null) return an; if ((an = (String) sctx.getAttribute(_key)) != null) return an; return an; }
From source file:org.apache.hadoop.hdfs.server.namenode.JspHelper.java
/** * Get {@link UserGroupInformation} and possibly the delegation token out of * the request./* w w w . j av a2 s.co m*/ * @param context the Servlet context * @param request the http request * @param conf configuration * @param secureAuthMethod the AuthenticationMethod used in secure mode. * @param tryUgiParameter Should it try the ugi parameter? * @return a new user from the request * @throws AccessControlException if the request has no token */ public static UserGroupInformation getUGI(ServletContext context, HttpServletRequest request, Configuration conf, final AuthenticationMethod secureAuthMethod, final boolean tryUgiParameter) throws IOException { final UserGroupInformation ugi; final String usernameFromQuery = getUsernameFromQuery(request, tryUgiParameter); final String doAsUserFromQuery = request.getParameter(DoAsParam.NAME); if (UserGroupInformation.isSecurityEnabled()) { final String remoteUser = request.getRemoteUser(); String tokenString = request.getParameter(DELEGATION_PARAMETER_NAME); if (tokenString != null) { Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>(); token.decodeFromUrlString(tokenString); SecurityUtil.setTokenService(token, NameNode.getAddress(conf)); token.setKind(DelegationTokenIdentifier.HDFS_DELEGATION_KIND); ByteArrayInputStream buf = new ByteArrayInputStream(token.getIdentifier()); DataInputStream in = new DataInputStream(buf); DelegationTokenIdentifier id = new DelegationTokenIdentifier(); id.readFields(in); if (context != null) { NameNode nn = (NameNode) context.getAttribute("name.node"); if (nn != null) { //Verify the token. nn.getNamesystem().getDelegationTokenSecretManager().verifyToken(id, token.getPassword()); } } ugi = id.getUser(); if (ugi.getRealUser() == null) { //non-proxy case checkUsername(ugi.getShortUserName(), usernameFromQuery); checkUsername(null, doAsUserFromQuery); } else { //proxy case checkUsername(ugi.getRealUser().getShortUserName(), usernameFromQuery); checkUsername(ugi.getShortUserName(), doAsUserFromQuery); ProxyUsers.authorize(ugi, request.getRemoteAddr(), conf); } ugi.addToken(token); ugi.setAuthenticationMethod(AuthenticationMethod.TOKEN); } else { if (remoteUser == null) { throw new IOException("Security enabled but user not " + "authenticated by filter"); } final UserGroupInformation realUgi = UserGroupInformation.createRemoteUser(remoteUser); checkUsername(realUgi.getShortUserName(), usernameFromQuery); // This is not necessarily true, could have been auth'ed by user-facing // filter realUgi.setAuthenticationMethod(secureAuthMethod); ugi = initUGI(realUgi, doAsUserFromQuery, request, true, conf); } } else { // Security's not on, pull from url final UserGroupInformation realUgi = usernameFromQuery == null ? getDefaultWebUser(conf) // not specified in request : UserGroupInformation.createRemoteUser(usernameFromQuery); realUgi.setAuthenticationMethod(AuthenticationMethod.SIMPLE); ugi = initUGI(realUgi, doAsUserFromQuery, request, false, conf); } if (LOG.isDebugEnabled()) LOG.debug("getUGI is returning: " + ugi.getShortUserName()); return ugi; }
From source file:org.apache.hadoop.gateway.AuditLoggingTest.java
@Test /**//from w ww. ja va 2s . c om * Empty filter chain. Two events with same correlation ID are expected: * * action=access request_type=uri outcome=unavailable * action=access request_type=uri outcome=success message=Response status: 404 */ public void testNoFiltersAudit() throws ServletException, IOException { FilterConfig config = EasyMock.createNiceMock(FilterConfig.class); EasyMock.replay(config); HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class); ServletContext context = EasyMock.createNiceMock(ServletContext.class); GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class); EasyMock.expect(request.getMethod()).andReturn(METHOD).anyTimes(); EasyMock.expect(request.getPathInfo()).andReturn(PATH).anyTimes(); EasyMock.expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes(); EasyMock.expect(request.getRemoteAddr()).andReturn(ADDRESS).anyTimes(); EasyMock.expect(request.getRemoteHost()).andReturn(HOST).anyTimes(); EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes(); EasyMock.expect(context.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(gatewayConfig) .anyTimes(); EasyMock.expect(gatewayConfig.getHeaderNameForRemoteAddress()).andReturn("Custom-Forwarded-For").anyTimes(); EasyMock.replay(request); EasyMock.replay(context); EasyMock.replay(gatewayConfig); HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain chain = EasyMock.createNiceMock(FilterChain.class); EasyMock.replay(chain); GatewayFilter gateway = new GatewayFilter(); gateway.init(config); gateway.doFilter(request, response, chain); gateway.destroy(); assertThat(CollectAppender.queue.size(), is(1)); Iterator<LoggingEvent> iterator = CollectAppender.queue.iterator(); LoggingEvent accessEvent = iterator.next(); verifyAuditEvent(accessEvent, CONTEXT_PATH + PATH, ResourceType.URI, Action.ACCESS, ActionOutcome.UNAVAILABLE, null, "Request method: GET"); }
From source file:org.apache.hadoop.gateway.AuditLoggingTest.java
@Test /**/*from w w w . ja va2 s.c om*/ * One NoOp filter in chain. Single audit event with same with specified request URI is expected: * * action=access request_type=uri outcome=unavailable */ public void testNoopFilter() throws ServletException, IOException, URISyntaxException { FilterConfig config = EasyMock.createNiceMock(FilterConfig.class); EasyMock.replay(config); HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class); ServletContext context = EasyMock.createNiceMock(ServletContext.class); GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class); EasyMock.expect(request.getMethod()).andReturn(METHOD).anyTimes(); EasyMock.expect(request.getPathInfo()).andReturn(PATH).anyTimes(); EasyMock.expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes(); EasyMock.expect(request.getRemoteAddr()).andReturn(ADDRESS).anyTimes(); EasyMock.expect(request.getRemoteHost()).andReturn(HOST).anyTimes(); EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes(); EasyMock.expect(context.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(gatewayConfig) .anyTimes(); EasyMock.expect(gatewayConfig.getHeaderNameForRemoteAddress()).andReturn("Custom-Forwarded-For").anyTimes(); EasyMock.replay(request); EasyMock.replay(context); EasyMock.replay(gatewayConfig); HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain chain = EasyMock.createNiceMock(FilterChain.class); EasyMock.replay(chain); Filter filter = EasyMock.createNiceMock(Filter.class); EasyMock.replay(filter); GatewayFilter gateway = new GatewayFilter(); gateway.addFilter("path", "filter", filter, null, null); gateway.init(config); gateway.doFilter(request, response, chain); gateway.destroy(); assertThat(CollectAppender.queue.size(), is(1)); Iterator<LoggingEvent> iterator = CollectAppender.queue.iterator(); LoggingEvent accessEvent = iterator.next(); verifyAuditEvent(accessEvent, CONTEXT_PATH + PATH, ResourceType.URI, Action.ACCESS, ActionOutcome.UNAVAILABLE, null, "Request method: GET"); }
From source file:org.apache.axis2.transport.http.AxisServlet.java
/** * Main init method//from ww w. jav a2 s . com * * @param config The ServletConfig * @throws ServletException */ @Override public void init(ServletConfig config) throws ServletException { // prevent this method from being called more than once per instance initCalled = true; super.init(config); try { this.servletConfig = config; ServletContext servletContext = servletConfig.getServletContext(); this.configContext = (ConfigurationContext) servletContext.getAttribute(CONFIGURATION_CONTEXT); if (configContext == null) { configContext = initConfigContext(config); config.getServletContext().setAttribute(CONFIGURATION_CONTEXT, configContext); } axisConfiguration = configContext.getAxisConfiguration(); initTransports(); initGetRequestProcessors(config); initParams(); } catch (Exception e) { throw new ServletException(e); } }