javax.servlet.ServletException Java Examples
The following examples show how to use
javax.servlet.ServletException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Logout.java From JavaVulnerableLab with GNU General Public License v2.0 | 6 votes |
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try { PrintWriter out = response.getWriter(); /* TODO output your page here. You may use following sample code. */ HttpSession session=request.getSession(); session.invalidate(); response.sendRedirect("index.jsp"); } catch(Exception e) { } }
Example #2
Source File: WebAppConfiguration.java From sakai with Educational Community License v2.0 | 6 votes |
@Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.setServletContext(servletContext); rootContext.register(ThymeleafConfig.class); servletContext.addListener(new SakaiContextLoaderListener(rootContext)); servletContext.addFilter("sakai.request", RequestFilter.class) .addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), true, "/*"); Dynamic servlet = servletContext.addServlet("sakai.onedrive", new DispatcherServlet(rootContext)); servlet.addMapping("/"); servlet.setLoadOnStartup(1); }
Example #3
Source File: LineitemUtil.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Removes lineitem. Throws exception if lineitem is not found. * * @param _content_id * @param _course_id * @throws PersistenceException * @throws ServletException */ public static void removeLineitem(String _content_id, String _course_id) throws PersistenceException, ServletException { BbPersistenceManager bbPm = PersistenceServiceFactory.getInstance().getDbPersistenceManager(); Container bbContainer = bbPm.getContainer(); ContentDbLoader courseDocumentLoader = ContentDbLoader.Default.getInstance(); LineitemDbPersister linePersister = LineitemDbPersister.Default.getInstance(); Id contentId = new PkId(bbContainer, CourseDocument.DATA_TYPE, _content_id); Content bbContent = courseDocumentLoader.loadById(contentId); //check isGradecenter option is ON and thus there should exist associated lineitem object if (!bbContent.getIsDescribed()) { return; } Id lineitemId = getLineitem(_content_id, _course_id, true); linePersister.deleteById(lineitemId); //Remove bbContentId -> lineitemid pair from the storage PortalExtraInfo pei = PortalUtil.loadPortalExtraInfo(null, null, LAMS_LINEITEM_STORAGE); ExtraInfo ei = pei.getExtraInfo(); ei.clearEntry(_content_id); PortalUtil.savePortalExtraInfo(pei); }
Example #4
Source File: SipGatewayManager.java From JVoiceXML with GNU Lesser General Public License v2.1 | 6 votes |
@Override protected void doSuccessResponse(final SipServletResponse response) throws ServletException, IOException { final String method = response.getRequest().getMethod(); if("REGISTER".equalsIgnoreCase(method)) { final int status = response.getStatus(); if(status == SipServletResponse.SC_OK) { final SipApplicationSession application = response.getApplicationSession(); final Gateway gateway = (Gateway)application.getAttribute(Gateway.class.getName()); final Address contact = response.getAddressHeader("Contact"); long expires = contact.getExpires() * 1000; clock.createTimer(application, expires, false, "REGISTER"); // Issue http://code.google.com/p/vnxivr/issues/detail?id=66 expires += TimeUtils.SECOND_IN_MILLIS * 30; application.setExpires(TimeUtils.millisToMinutes(expires)); if(logger.isDebugEnabled()) { final StringBuilder buffer = new StringBuilder(); buffer.append("Successfully registered\n"); buffer.append(gateway.toString()).append("\n"); buffer.append("for a duration of ").append(expires).append(" seconds."); logger.debug(buffer.toString()); } } } }
Example #5
Source File: TestCorsFilter.java From Tomcat7.0.67 with Apache License 2.0 | 6 votes |
/** * Tests if a non-simple request is given to simple request handler. * * @throws IOException * @throws ServletException */ @Test(expected = IllegalArgumentException.class) public void testNotSimple() throws IOException, ServletException { TesterHttpServletRequest request = new TesterHttpServletRequest(); request.setHeader(CorsFilter.REQUEST_HEADER_ORIGIN, TesterFilterConfigs.HTTPS_WWW_APACHE_ORG); request.setHeader( CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD, "PUT"); request.setHeader( CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS, "Content-Type"); request.setMethod("OPTIONS"); TesterHttpServletResponse response = new TesterHttpServletResponse(); CorsFilter corsFilter = new CorsFilter(); corsFilter.init(TesterFilterConfigs .getDefaultFilterConfig()); corsFilter.handleSimpleCORS(request, response, filterChain); }
Example #6
Source File: AsyncContextImpl.java From Tomcat8-Source-Read with MIT License | 6 votes |
protected void doInternalDispatch() throws ServletException, IOException { if (log.isDebugEnabled()) { logDebug("intDispatch"); } try { Runnable runnable = dispatch; dispatch = null; runnable.run(); if (!request.isAsync()) { fireOnComplete(); } } catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); } }
Example #7
Source File: GetTestCaseList.java From cerberus-source with GNU General Public License v3.0 | 6 votes |
@Override protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); ITestCaseService testService = appContext.getBean(ITestCaseService.class); PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS); String test = policy.sanitize(httpServletRequest.getParameter("test")); JSONArray array = new JSONArray(); JSONObject jsonObject = new JSONObject(); for (TestCase testcase : testService.findTestCaseByTest(test)) { array.put(testcase.getTestCase()); } try { jsonObject.put("testcasesList", array); httpServletResponse.setContentType("application/json"); httpServletResponse.getWriter().print(jsonObject.toString()); } catch (JSONException exception) { LOG.warn(exception.toString()); } }
Example #8
Source File: StartJobServletTest.java From pentaho-kettle with Apache License 2.0 | 6 votes |
@Test @PrepareForTest( { Encode.class } ) public void testStartJobServletEscapesHtmlWhenTransNotFound() throws ServletException, IOException { HttpServletRequest mockHttpServletRequest = mock( HttpServletRequest.class ); HttpServletResponse mockHttpServletResponse = mock( HttpServletResponse.class ); StringWriter out = new StringWriter(); PrintWriter printWriter = new PrintWriter( out ); PowerMockito.spy( Encode.class ); when( mockHttpServletRequest.getContextPath() ).thenReturn( StartJobServlet.CONTEXT_PATH ); when( mockHttpServletRequest.getParameter( anyString() ) ).thenReturn( ServletTestUtils.BAD_STRING_TO_TEST ); when( mockHttpServletResponse.getWriter() ).thenReturn( printWriter ); startJobServlet.doGet( mockHttpServletRequest, mockHttpServletResponse ); assertFalse( ServletTestUtils.hasBadText( ServletTestUtils.getInsideOfTag( "H1", out.toString() ) ) ); PowerMockito.verifyStatic( atLeastOnce() ); Encode.forHtml( anyString() ); }
Example #9
Source File: RestServlet.java From mdw with Apache License 2.0 | 5 votes |
@Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CodeTimer timer = new CodeTimer("RestServlet.doDelete()", true); Map<String,String> metaInfo = buildMetaInfo(request); try { String responseString = handleRequest(request, response, metaInfo); response.getOutputStream().print(responseString); } catch (ServiceException ex) { logger.error(ex.getMessage(), ex); response.setStatus(ex.getCode()); response.getWriter().println(createErrorResponseMessage(request, metaInfo, ex)); } finally { timer.stopAndLogTiming(""); } }
Example #10
Source File: BenchmarkTest02475.java From Benchmark with GNU General Public License v2.0 | 5 votes |
private static String doSomething(HttpServletRequest request, String param) throws ServletException, IOException { String bar = "safe!"; java.util.HashMap<String,Object> map43776 = new java.util.HashMap<String,Object>(); map43776.put("keyA-43776", "a-Value"); // put some stuff in the collection map43776.put("keyB-43776", param); // put it in a collection map43776.put("keyC", "another-Value"); // put some stuff in the collection bar = (String)map43776.get("keyB-43776"); // get it back out return bar; }
Example #11
Source File: AuthenticationSuccessHandler.java From runscore with Apache License 2.0 | 5 votes |
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { UserAccountDetails user = (UserAccountDetails) authentication.getPrincipal(); userAccountService.updateLatelyLoginTime(user.getUserAccountId()); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.println(JSONObject.toJSONString(Result.success().setMsg("登录成功"))); out.flush(); out.close(); }
Example #12
Source File: RefreshTokenFilter.java From cubeai with Apache License 2.0 | 5 votes |
/** * Check access token cookie and refresh it, if it is either not present, expired or about to expire. */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; try { httpServletRequest = refreshTokensIfExpiring(httpServletRequest, httpServletResponse); } catch (ClientAuthenticationException ex) { log.warn("Security exception: could not refresh tokens", ex); httpServletRequest = authenticationService.stripTokens(httpServletRequest); } filterChain.doFilter(httpServletRequest, servletResponse); }
Example #13
Source File: SafeDelegatingFilterProxy.java From sakai with Educational Community License v2.0 | 5 votes |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (enabled) { super.doFilter(request, response, filterChain); return; } filterChain.doFilter(request, response); }
Example #14
Source File: BenchmarkTest01261.java From Benchmark with GNU General Public License v2.0 | 5 votes |
public String doSomething(HttpServletRequest request, String param) throws ServletException, IOException { // Chain a bunch of propagators in sequence String a34194 = param; //assign StringBuilder b34194 = new StringBuilder(a34194); // stick in stringbuilder b34194.append(" SafeStuff"); // append some safe content b34194.replace(b34194.length()-"Chars".length(),b34194.length(),"Chars"); //replace some of the end content java.util.HashMap<String,Object> map34194 = new java.util.HashMap<String,Object>(); map34194.put("key34194", b34194.toString()); // put in a collection String c34194 = (String)map34194.get("key34194"); // get it back out String d34194 = c34194.substring(0,c34194.length()-1); // extract most of it String e34194 = new String( org.apache.commons.codec.binary.Base64.decodeBase64( org.apache.commons.codec.binary.Base64.encodeBase64( d34194.getBytes() ) )); // B64 encode and decode it String f34194 = e34194.split(" ")[0]; // split it on a space org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String bar = thing.doSomething(f34194); // reflection return bar; }
Example #15
Source File: GatherScheduledJobResultService.java From jumbune with GNU Lesser General Public License v3.0 | 5 votes |
@POST public Response processPost(){ StringBuilder builder = new StringBuilder(); try { doPost(); builder.append("SUCCESS"); } catch (ServletException | IOException e) { builder.append("FAILURE due to: "+e); } GenericEntity<String> entity = new GenericEntity<String>( builder.toString()) { }; return Response.ok(entity).build(); }
Example #16
Source File: AsyncStockServlet.java From tomcatsrc with Apache License 2.0 | 5 votes |
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.isAsyncStarted()) { req.getAsyncContext().complete(); } else if (req.isAsyncSupported()) { AsyncContext actx = req.startAsync(); actx.addListener(this); resp.setContentType("text/plain"); clients.add(actx); if (clientcount.incrementAndGet()==1) { ticker.addTickListener(this); } } else { new Exception("Async Not Supported").printStackTrace(); resp.sendError(400,"Async is not supported."); } }
Example #17
Source File: ExecuteJobServletTest.java From pentaho-kettle with Apache License 2.0 | 5 votes |
@Test public void testExecuteJobServletTest() throws ServletException, IOException, KettleException { doReturn( ExecuteJobServlet.CONTEXT_PATH ).when( mockHttpServletRequest ).getContextPath(); doReturn( REPOSITORY_NAME ).when( mockHttpServletRequest ).getParameter( "rep" ); doReturn( AUTHORIZED_USER ).when( mockHttpServletRequest ).getParameter( "user" ); doReturn( PASSWORD ).when( mockHttpServletRequest ).getParameter( "pass" ); doReturn( JOB_NAME ).when( mockHttpServletRequest ).getParameter( "job" ); doReturn( LEVEL ).when( mockHttpServletRequest ).getParameter( "level" ); PowerMockito.mockStatic( Encr.class ); when( Encr.decryptPasswordOptionallyEncrypted( PASSWORD ) ).thenReturn( PASSWORD ); doReturn( repository ).when( spyExecuteJobServlet ).openRepository( REPOSITORY_NAME, AUTHORIZED_USER, PASSWORD ); JobMeta jobMeta = buildJobMeta(); RepositoryDirectoryInterface repositoryDirectoryInterface = mock( RepositoryDirectoryInterface.class ); doReturn( repositoryDirectoryInterface ).when( repository ).loadRepositoryDirectoryTree(); doReturn( mock( RepositoryDirectoryInterface.class ) ).when( repositoryDirectoryInterface ) .findDirectory( anyString() ); doReturn( mock( ObjectId.class ) ).when( repository ) .getJobId( anyString(), any( RepositoryDirectoryInterface.class ) ); doReturn( jobMeta ).when( repository ).loadJob( any( ObjectId.class ), anyString() ); doReturn( Collections.emptyEnumeration() ).when( mockHttpServletRequest ).getParameterNames(); StringWriter out = mockWriter(); spyExecuteJobServlet.doGet( mockHttpServletRequest, spyHttpServletResponse ); assertTrue( out.toString().contains( WebResult.STRING_OK ) ); assertTrue( out.toString().contains( "Job started" ) ); }
Example #18
Source File: RegistryAppInitializer.java From konker-platform with Apache License 2.0 | 5 votes |
@Override public void onStartup(ServletContext servletContext) throws ServletException { super.onStartup(servletContext); servletContext.addListener(new RequestContextListener()); // verifying configs for features activation Set<String> profiles = new HashSet<String>(); if (isEmailFeaturesEnabled()) { profiles.add("email"); } if (isCdnFeaturesEnabled()) { profiles.add("cdn"); } if (isSslFeaturesEnabled()) { profiles.add("ssl"); } servletContext.setInitParameter("spring.profiles.active", StringUtils.arrayToCommaDelimitedString(profiles.toArray())); }
Example #19
Source File: SimpleCORSFilter.java From griffin with Apache License 2.0 | 5 votes |
@Override public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept"); chain.doFilter(req, res); }
Example #20
Source File: SmsLoginFilter.java From daming with Apache License 2.0 | 5 votes |
@Override public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String jwt = request.getHeader("X-SMS-VERIFICATION-JWT"); SmsVerificationClaims claims = smsVerificationJwtVerifier.verify(jwt, "SMS_LOGIN"); String mobile = claims.getMobile(); return userRepository.mustFindByMobile(mobile); }
Example #21
Source File: CXFJAXRSFilter.java From tomee with Apache License 2.0 | 5 votes |
@Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (!HttpServletRequest.class.isInstance(request)) { chain.doFilter(request, response); return; } final HttpServletRequest httpServletRequest = HttpServletRequest.class.cast(request); final HttpServletResponse httpServletResponse = HttpServletResponse.class.cast(response); if (!this.delegate.isCXFResource(httpServletRequest)) { chain.doFilter(request, response); return; } if (CxfRsHttpListener.TRY_STATIC_RESOURCES) { // else 100% JAXRS if (servletMappingIsUnderRestPath(httpServletRequest)) { chain.doFilter(request, response); return; } final InputStream staticContent = delegate.findStaticContent(httpServletRequest, welcomeFiles); if (staticContent != null) { chain.doFilter(request, response); return; } } try { delegate.doInvoke( new ServletRequestAdapter(httpServletRequest, httpServletResponse, request.getServletContext()), new ServletResponseAdapter(httpServletResponse)); } catch (final Exception e) { throw new ServletException("Error processing webservice request", e); } }
Example #22
Source File: RestPublicLoginProcessingFilter.java From Groza with Apache License 2.0 | 5 votes |
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!HttpMethod.POST.name().equals(request.getMethod())) { if(log.isDebugEnabled()) { log.debug("Authentication method not supported. Request method: " + request.getMethod()); } throw new AuthMethodNotSupportedException("Authentication method not supported"); } PublicLoginRequest loginRequest; try { loginRequest = objectMapper.readValue(request.getReader(), PublicLoginRequest.class); } catch (Exception e) { throw new AuthenticationServiceException("Invalid public login request payload"); } if (StringUtils.isBlank(loginRequest.getPublicId())) { throw new AuthenticationServiceException("Public Id is not provided"); } UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, loginRequest.getPublicId()); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, ""); return this.getAuthenticationManager().authenticate(token); }
Example #23
Source File: SecuredFilter.java From component-runtime with Apache License 2.0 | 5 votes |
@Override public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { if (endpointSecurityService.isAllowed(servletRequest) && canCall(servletRequest)) { filterChain.doFilter(servletRequest, servletResponse); return; } final HttpServletResponse response = HttpServletResponse.class.cast(servletResponse); response.setStatus(HttpServletResponse.SC_NOT_FOUND); }
Example #24
Source File: SwaggerServlet.java From usergrid with Apache License 2.0 | 5 votes |
@Override public void init( FilterConfig config ) throws ServletException { if (logger.isTraceEnabled()) { logger.trace("init(FilterConfig paramFilterConfig)"); } if ( sc == null ) { sc = config.getServletContext(); } properties = ( Properties ) getSpringBeanFromWeb( "properties" ); loadSwagger(); }
Example #25
Source File: SetCookie.java From journaldev with MIT License | 5 votes |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Cookie[] requestCookies = request.getCookies(); out.write("<html><head></head><body>"); out.write("<h3>Hello Browser!!</h3>"); if(requestCookies != null){ out.write("<h3>Request Cookies:</h3>"); for(Cookie c : requestCookies){ out.write("Name="+c.getName()+", Value="+c.getValue()+", Comment="+c.getComment() +", Domain="+c.getDomain()+", MaxAge="+c.getMaxAge()+", Path="+c.getPath() +", Version="+c.getVersion()); out.write("<br>"); } } //Set cookies for counter, accessible to only this servlet count++; Cookie counterCookie = new Cookie("Counter", String.valueOf(count)); //add some description to be viewed in browser cookie viewer counterCookie.setComment("SetCookie Counter"); //setting max age to be 1 day counterCookie.setMaxAge(24*60*60); //set path to make it accessible to only this servlet counterCookie.setPath("/ServletCookie/cookie/SetCookie"); //adding cookie to the response response.addCookie(counterCookie); //set a domain specific cookie Cookie domainCookie = new Cookie("Test", "Test Cookie"+String.valueOf(count)); domainCookie.setComment("Test Cookie"); response.addCookie(domainCookie); out.write("</body></html>"); }
Example #26
Source File: RequestedSessionIdServlet.java From quarkus-http with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { switch (req.getParameter("action")) { case "create": req.getSession(true); resp.getWriter().write(req.getRequestedSessionId()); break; case "destroy": req.getSession().invalidate(); resp.getWriter().write(req.getRequestedSessionId()); break; case "destroycreate": req.getSession().invalidate(); req.getSession(true); resp.getWriter().write(req.getRequestedSessionId()); break; case "change": req.changeSessionId(); resp.getWriter().write(req.getRequestedSessionId()); break; case "timeout": req.getSession(true).setMaxInactiveInterval(1); resp.getWriter().write(req.getRequestedSessionId()); break; case "isvalid": resp.getWriter().write(req.isRequestedSessionIdValid() + ""); break; case "default": resp.getWriter().write(req.getRequestedSessionId()); break; } }
Example #27
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 5 votes |
/** * Checks that the file extension is supported. */ private void checkFileExtension(String fileName) throws ServletException { if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) { String[] allowedExt = { ".jpg", ".jpeg", ".png", ".gif" }; for (String ext : allowedExt) { if (fileName.endsWith(ext)) { return; } } throw new ServletException("file must be an image"); } }
Example #28
Source File: RestAuthenticationEntryPoint.java From HIS with Apache License 2.0 | 5 votes |
@Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage()))); response.getWriter().flush(); }
Example #29
Source File: SessionUserFilter.java From VulnerableJavaWebApplication with MIT License | 5 votes |
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; User user = (User) request.getSession().getAttribute("sessionUser"); if (user == null) { response.sendRedirect("/login"); } else { chain.doFilter(request, response); } }
Example #30
Source File: OpenIdCallbackLoginFilter.java From alf.io with GNU General Public License v3.0 | 5 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; if (requestMatcher.matches(req)) { super.doFilter(req, res, chain); } chain.doFilter(request, response); }