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 Project: Tomcat7.0.67   Author: tryandcatch   File: TestCorsFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source Project: pentaho-kettle   Author: pentaho   File: StartJobServletTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #3
Source Project: cerberus-source   Author: cerberustesting   File: GetTestCaseList.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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 #4
Source Project: JavaVulnerableLab   Author: CSPF-Founder   File: Logout.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #5
Source Project: lams   Author: lamsfoundation   File: LineitemUtil.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
    * 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 #6
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: AsyncContextImpl.java    License: MIT License 6 votes vote down vote up
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 Project: JVoiceXML   Author: JVoiceXML   File: SipGatewayManager.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #8
Source Project: sakai   Author: sakaiproject   File: WebAppConfiguration.java    License: Educational Community License v2.0 6 votes vote down vote up
@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 #9
Source Project: griffin   Author: apache   File: SimpleCORSFilter.java    License: Apache License 2.0 5 votes vote down vote up
@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 #10
Source Project: spring-analysis-note   Author: Vip-Augus   File: InternalResourceView.java    License: MIT License 5 votes vote down vote up
/**
 * Render the internal resource given the specified model.
 * This includes setting the model as request attributes.
 * 在给定指定模型的情况下呈现内部资源。这包括将模型设置为请求属性
 */
@Override
protected void renderMergedOutputModel(
		Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

	// Expose the model object as request attributes.
	exposeModelAsRequestAttributes(model, request);

	// Expose helpers as request attributes, if any.
	exposeHelpers(request);

	// Determine the path for the request dispatcher.
	String dispatcherPath = prepareForRendering(request, response);

	// Obtain a RequestDispatcher for the target resource (typically a JSP).
	RequestDispatcher rd = getRequestDispatcher(request, dispatcherPath);
	if (rd == null) {
		throw new ServletException("Could not get RequestDispatcher for [" + getUrl() +
				"]: Check that the corresponding file exists within your web application archive!");
	}

	// If already included or response already committed, perform include, else forward.
	if (useInclude(request, response)) {
		response.setContentType(getContentType());
		if (logger.isDebugEnabled()) {
			logger.debug("Including [" + getUrl() + "]");
		}
		rd.include(request, response);
	}

	else {
		// Note: The forwarded resource is supposed to determine the content type itself.
		if (logger.isDebugEnabled()) {
			logger.debug("Forwarding to [" + getUrl() + "]");
		}
		rd.forward(request, response);
	}
}
 
Example #11
Source Project: konker-platform   Author: KonkerLabs   File: RegistryAppInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@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 #12
Source Project: pentaho-kettle   Author: pentaho   File: ExecuteJobServletTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 #13
Source Project: mdw   Author: CenturyLinkCloud   File: RestServlet.java    License: Apache License 2.0 5 votes vote down vote up
@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 #14
Source Project: tomcatsrc   Author: wangyingjie   File: AsyncStockServlet.java    License: Apache License 2.0 5 votes vote down vote up
@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 #15
Source Project: jumbune   Author: Impetus   File: GatherScheduledJobResultService.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 Project: Benchmark   Author: OWASP   File: BenchmarkTest01261.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 #17
Source Project: Benchmark   Author: OWASP   File: BenchmarkTest00051.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	// some code
	response.setContentType("text/html;charset=UTF-8");
	

	org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
	String param = scr.getTheValue("BenchmarkTest00051");

	
	String a1 = "";
	String a2 = "";
	String osName = System.getProperty("os.name");
       if (osName.indexOf("Windows") != -1) {
       	a1 = "cmd.exe";
       	a2 = "/c";
       } else {
       	a1 = "sh";
       	a2 = "-c";
       }
       String[] args = {a1, a2, "echo " + param};

	ProcessBuilder pb = new ProcessBuilder(args);
	
	try {
		Process p = pb.start();
		org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response);
	} catch (IOException e) {
		System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.lang.String[]) Test Case");
           throw new ServletException(e);
	}
}
 
Example #18
Source Project: cubeai   Author: cube-ai   File: RefreshTokenFilter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 #19
Source Project: runscore   Author: bbhpgh   File: AuthenticationSuccessHandler.java    License: Apache License 2.0 5 votes vote down vote up
@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 #20
Source Project: Benchmark   Author: OWASP   File: BenchmarkTest02475.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 #21
Source Project: sakai   Author: sakaiproject   File: SafeDelegatingFilterProxy.java    License: Educational Community License v2.0 5 votes vote down vote up
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 #22
Source Project: daming   Author: TheBund1st   File: SmsLoginFilter.java    License: Apache License 2.0 5 votes vote down vote up
@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 #23
Source Project: tomee   Author: apache   File: CXFJAXRSFilter.java    License: Apache License 2.0 5 votes vote down vote up
@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 #24
Source Project: Groza   Author: IoT-Technology   File: RestPublicLoginProcessingFilter.java    License: Apache License 2.0 5 votes vote down vote up
@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 #25
Source Project: component-runtime   Author: Talend   File: SecuredFilter.java    License: Apache License 2.0 5 votes vote down vote up
@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 #26
Source Project: usergrid   Author: apache   File: SwaggerServlet.java    License: Apache License 2.0 5 votes vote down vote up
@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 #27
Source Project: journaldev   Author: journaldev   File: SetCookie.java    License: MIT License 5 votes vote down vote up
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 #28
Source Project: quarkus-http   Author: quarkusio   File: RequestedSessionIdServlet.java    License: Apache License 2.0 5 votes vote down vote up
@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 #29
Source Project: getting-started-java   Author: GoogleCloudPlatform   File: CloudStorageHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 #30
Source Project: HIS   Author: ZainZhao   File: RestAuthenticationEntryPoint.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}