@Override public void init() throws ServletException { format = getServletConfig().getInitParameter("outputFormat"); if (format == null || format.trim().isEmpty()) { throw new ServletException("Invalid outputFormat setting."); String spacingStr = getServletConfig().getInitParameter("preserveSpacing"); if (spacingStr == null || spacingStr.trim().isEmpty()) { throw new ServletException("Invalid preserveSpacing setting."); spacing = "true".equals(spacingStr); String path = getServletContext().getRealPath("/WEB-INF/data/models"); for (String classifier : new File(path).list()) { classifiers.add(classifier); CRFClassifier model = null; String filename = "/WEB-INF/data/models/" + classifier; InputStream is = getServletConfig().getServletContext().getResourceAsStream(filename); throw new ServletException("File not found. Filename = " + filename);
private PersistenceUnitInjectionResolver(ServletConfig servletConfig) { for (final Enumeration parameterNames = servletConfig.getInitParameterNames(); parameterNames.hasMoreElements(); ) { final String key = (String) parameterNames.nextElement(); if (key.startsWith(PERSISTENCE_UNIT_PREFIX)) { persistenceUnits.put(key.substring(PERSISTENCE_UNIT_PREFIX.length()), "java:comp/env/" + servletConfig.getInitParameter(key)); } } }
/** * Create new ServletConfigPropertyValues. * @param config the ServletConfig we'll use to take PropertyValues from * @param requiredProperties set of property names we need, where * we can't accept default values * @throws ServletException if any required properties are missing */ public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties) throws ServletException { Set<String> missingProps = (!CollectionUtils.isEmpty(requiredProperties) ? new HashSet<>(requiredProperties) : null); Enumeration<String> paramNames = config.getInitParameterNames(); while (paramNames.hasMoreElements()) { String property = paramNames.nextElement(); Object value = config.getInitParameter(property); addPropertyValue(new PropertyValue(property, value)); if (missingProps != null) { missingProps.remove(property); } } // Fail if we are still missing properties. if (!CollectionUtils.isEmpty(missingProps)) { throw new ServletException( "Initialization from ServletConfig for servlet '" + config.getServletName() + "' failed; the following required properties were missing: " + StringUtils.collectionToDelimitedString(missingProps, ", ")); } } }
public String getInitParameter(String name) { String param = initParams.get(name); if (param == null) { param = sc.getInitParameter(name); if (param == null && useServletContextParameters) { param = sc.getServletContext().getInitParameter(name); } } return param; }
private String getServletPath(ServletConfig config) { String name = config.getServletName(); ServletRegistration registration = config.getServletContext().getServletRegistration(name); if (registration == null) { throw new IllegalStateException("ServletRegistration not found for Servlet '" + name + "'"); } Collection<String> mappings = registration.getMappings(); if (mappings.size() == 1) { String mapping = mappings.iterator().next(); if (mapping.equals("/")) { return ""; } if (mapping.endsWith("/*")) { String path = mapping.substring(0, mapping.length() - 2); if (!path.isEmpty() && logger.isDebugEnabled()) { logger.debug("Found servlet mapping prefix '" + path + "' for '" + name + "'"); } return path; } } throw new IllegalArgumentException("Expected a single Servlet mapping: " + "either the default Servlet mapping (i.e. '/'), " + "or a path based mapping (e.g. '/*', '/foo/*'). " + "Actual mappings: " + mappings + " for Servlet '" + name + "'"); }
final ServletContext context = getServletConfig().getServletContext(); for (final Enumeration<String> e = context.getInitParameterNames(); e .hasMoreElements();) { final String name = e.nextElement(); initParameters.setProperty(name, context.getInitParameter(name)); .getInitParameterNames(); e.hasMoreElements();) { final String name = e.nextElement(); initParameters.setProperty(name, getServletConfig().getInitParameter(name));
@Test public void testNotFound() throws ServletException, IOException { StaticContentServlet servlet = new StaticContentServlet(); ServletContext context = mock(ServletContext.class); when(context.getServletContextName()).thenReturn("foo"); when(context.getMimeType(anyString())).thenReturn("image/jpeg"); ServletConfig config = mock(ServletConfig.class); when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Arrays.asList("root"))); when(config.getInitParameter("root")).thenReturn(getFileSystemRoot()); when(config.getServletContext()).thenReturn(context); servlet.init(config); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getMethod()).thenReturn("GET"); when(request.getPathInfo()).thenReturn("/missing.jpg"); when(request.getRequestURI()).thenReturn("/foo/missing.jpg"); when(request.getContextPath()).thenReturn("/foo"); HttpServletResponse response = mock(HttpServletResponse.class); servlet.service(request, response); verify(response).sendError(HttpServletResponse.SC_NOT_FOUND, "/foo/missing.jpg"); }
Map<String, String> parameterMap = new HashMap<>(); if (servletContext != null) { Enumeration<?> paramNameEnum = servletContext.getInitParameterNames(); while (paramNameEnum.hasMoreElements()) { String paramName = (String) paramNameEnum.nextElement(); parameterMap.put(paramName, servletContext.getInitParameter(paramName)); Enumeration<?> paramNameEnum = servletConfig.getInitParameterNames(); while (paramNameEnum.hasMoreElements()) { String paramName = (String) paramNameEnum.nextElement(); parameterMap.put(paramName, servletConfig.getInitParameter(paramName)); Map<String, Object> attributeMap = new HashMap<>(); if (servletContext != null) { Enumeration<?> attrNameEnum = servletContext.getAttributeNames(); while (attrNameEnum.hasMoreElements()) { String attrName = (String) attrNameEnum.nextElement();
/***************************************************************************** * Private Methods ****************************************************************************/ private void loadResources(ServletConfig config) { ServletContext servletContext = config.getServletContext(); _factory.setServletContext(servletContext); for (Enumeration<?> en = config.getInitParameterNames(); en.hasMoreElements();) { String name = (String) en.nextElement(); String value = config.getInitParameter(name); if (INIT_PARAM_PREFIX.equals(name)) { _factory.setPrefix(value); } else if (name.startsWith(INIT_PARAM_RESOURCE)) { String resourceName = name.substring(INIT_PARAM_RESOURCE.length()); try { Class<?> resourceType = Class.forName(value); _factory.addResource(resourceType); } catch (ClassNotFoundException ex) { servletContext.log("error loading resource name=" + resourceName + " type=" + value, ex); } catch (IOException ex) { servletContext.log("error creating resource name=" + resourceName + " type=" + value, ex); } } } servletContext.setAttribute("resources", _factory.getBundles()); }
final Enumeration initParams = servletConfig.getInitParameterNames(); while (initParams.hasMoreElements()) { final String initParamName = (String) initParams.nextElement();
@Override public void init() { Properties props = new Properties(); // Config parameters Enumeration<?> e = getInitParameterNames(); while (e.hasMoreElements()) { String name = (String)e.nextElement(); props.put(name, getInitParameter(name)); } boolean initialize = getServletConfig().getInitParameter(SKIP_INIT_NAME) != null; if (getServletContext().getAttribute(INIT_ATTR) != null) { if (initialize) { System.err.println("Jython has already been initialized in this context, not " + "initializing for " + getServletName() + ". Add " + SKIP_INIT_NAME + " to as an init param to this servlet's configuration to indicate this " + "is expected."); } } else if (initialize) { init(props, getServletContext()); } reset(); }
private void doAuthentication(HttpServletRequest req, HttpServletResponse resp) throws EntitlementCacheUpdateServletException { String username = req.getParameter(USERNAME_STRING); String password = req.getParameter(PSWD_STRING); String remoteIp = req.getServerName(); if (authenticate(username, password, remoteIp)) { RequestDispatcher requestDispatcher = req.getRequestDispatcher(UPDATE_CACHE); String subjectScope = EntitlementCacheUpdateServletDataHolder.getInstance().getServletConfig().getServletContext() .getInitParameter(SUBJECT_SCOPE); String subjectAttributeName = EntitlementCacheUpdateServletDataHolder.getInstance().getServletConfig().getServletContext() .getInitParameter("subjectAttributeName"); if (subjectScope.equals(EntitlementConstants.REQUEST_PARAM)) { requestDispatcher = req.getRequestDispatcher(UPDATE_CACHE + "?" + subjectAttributeName + "=" + username); } else if (subjectScope.equals(EntitlementConstants.REQUEST_ATTIBUTE)) { req.setAttribute(subjectAttributeName, username); } else if (subjectScope.equals(EntitlementConstants.SESSION)) { req.getSession().setAttribute(subjectAttributeName, username); } else { resp.setHeader("Authorization", Base64Utils.encode((username + ":" + password).getBytes(Charset.forName("UTF-8")))); } try { requestDispatcher.forward(req, resp); } catch (Exception e) { log.error("Error occurred while dispatching request to /updateCacheAuth.do", e); throw new EntitlementCacheUpdateServletException("Error occurred while dispatching request to /updateCacheAuth.do", e); } } else { showAuthPage(req, resp); } }
protected void doIt(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // if they clicked the install button... if ("install".equalsIgnoreCase(req.getParameter("action"))) { // If not already installed, try to install if (installer.getStatus() == NONE) { attempts++; paths.reset(); installer.reset(); paths.setCatalinaHomeDir(req.getParameter("catalinaHome")); paths.setCatalinaBaseDir(req.getParameter("catalinaBase")); paths.setServerXmlFile(req.getParameter("serverXml")); if (paths.verify()) { installer.installAll(); } } // send redirect to avoid double post lameness res.sendRedirect(req.getRequestURI()); } else { req.setAttribute("installer", installer); req.setAttribute("paths", paths); RequestDispatcher rd = servletConfig.getServletContext().getRequestDispatcher("/installer-view.jsp"); rd.forward(req,res); } }
/** * Test method for {@link org.ovirt.engine.core.FileServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}. */ @Test public void testDoGet3() throws ServletException, IOException { when(mockConfig.getInitParameter("cache")).thenReturn("false"); when(mockConfig.getInitParameter("file")).thenReturn(file.getParent()); testServlet.init(mockConfig); when(mockRequest.getPathInfo()).thenReturn(file.getName()); ServletOutputStream responseOut = mock(ServletOutputStream.class); when(mockResponse.getOutputStream()).thenReturn(responseOut); testServlet.doGet(mockRequest, mockResponse); //Make sure cache is disabled verify(mockResponse, never()).setHeader(eq("ETag"), any()); //Make sure something is written to the output stream (assuming it is the file). verify(responseOut).write(any(), eq(0), anyInt()); }
private void publishRequestHandledEvent(HttpServletRequest request, HttpServletResponse response, long startTime, @Nullable Throwable failureCause) { if (this.publishEvents && this.webApplicationContext != null) { // Whether or not we succeeded, publish an event. long processingTime = System.currentTimeMillis() - startTime; this.webApplicationContext.publishEvent( new ServletRequestHandledEvent(this, request.getRequestURI(), request.getRemoteAddr(), request.getMethod(), getServletConfig().getServletName(), WebUtils.getSessionId(request), getUsernameForRequest(request), processingTime, failureCause, response.getStatus())); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestURI = req.getRequestURI(); int index = (requestURI.indexOf("/resources/")) + 10; String resourceName = (requestURI.substring(index)); resp.setHeader("Access-Control-Allow-Origin", "*"); resp.getWriter().write( resourcesCache.get(resourceName, getServletConfig() .getServletContext())); }
protected void redirect(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException { boolean customServletPath = dispatcherServletPath != null; String theServletPath = customServletPath ? dispatcherServletPath : "/"; ServletContext sc = super.getServletContext(); RequestDispatcher rd = dispatcherServletName != null ? sc.getNamedDispatcher(dispatcherServletName) : sc.getRequestDispatcher((theServletPath + pathInfo).replace("//", "/")); if (rd == null) { String errorMessage = "No RequestDispatcher can be created for path " + pathInfo; if (dispatcherServletName != null) { errorMessage += ", dispatcher name: " + dispatcherServletName; } throw new ServletException(errorMessage); } try { for (Map.Entry<String, String> entry : redirectAttributes.entrySet()) { request.setAttribute(entry.getKey(), entry.getValue()); } HttpServletRequest servletRequest = new HttpServletRequestRedirectFilter(request, pathInfo, theServletPath, customServletPath); if (PropertyUtils.isTrue(getServletConfig().getInitParameter(REDIRECT_WITH_INCLUDE_PARAMETER))) { rd.include(servletRequest, response); } else { rd.forward(servletRequest, response); } } catch (Throwable ex) { throw new ServletException("RequestDispatcher for path " + pathInfo + " has failed", ex); } }
private Object createPojoInstance() throws ServletException { ServletContext context = getServletConfig().getServletContext(); String pojoClassId = context.getInitParameter(POJO_CLASS); if (pojoClassId == null) return null; Class pojoClass = (Class) context.getAttribute(pojoClassId); if (pojoClass == null) return null; try { Object instance = pojoClass.newInstance(); return instance; } catch (Exception e) { throw new ServletException("Unable to instantiate POJO WebService class: " + pojoClass.getName(), e); } }
public void forward(String relativePath) throws ServletException, IOException { ServletContext context = servlet.getServletConfig().getServletContext(); String baseURI; String requestURI = request.getRequestURI(); if(relativePath.startsWith("/")){ baseURI = requestURI.substring(0, request.getContextPath().length()); }else{ baseURI = requestURI.substring(0, requestURI.lastIndexOf("/")); } context.getRequestDispatcher(baseURI+relativePath).forward(request, response); }
try { String configFile = cfg.getInitParameter("config-file"); String shutdownPref = cfg.getInitParameter("shutdown-on-unload"); String shutdownWaitPref = cfg.getInitParameter("wait-on-shutdown"); if (shutdownPref != null) { waitOnShutdown = Boolean.valueOf(shutdownWaitPref).booleanValue(); .getInitParameter("start-scheduler-on-load"); String startDelayS = cfg.getInitParameter("start-delay-seconds"); try { if(startDelayS != null && startDelayS.trim().length() > 0) String factoryKey = cfg.getInitParameter("servlet-context-factory-key"); if (factoryKey == null) { factoryKey = QUARTZ_FACTORY_KEY; cfg.getServletContext().setAttribute(factoryKey, factory); String servletCtxtKey = cfg.getInitParameter("scheduler-context-servlet-context-key"); if (servletCtxtKey != null) { log("Storing the ServletContext in the scheduler context at key: " + servletCtxtKey); scheduler.getContext().put(servletCtxtKey, cfg.getServletContext()); throw new ServletException(e);