Java Code Examples for javax.servlet.http.HttpServletResponse

The following are top voted examples for showing how to use javax.servlet.http.HttpServletResponse. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ralasafe   File: DesignerAction.java   Source Code and License 10 votes vote down vote up
protected void doGet( HttpServletRequest req, HttpServletResponse resp )
		throws ServletException, IOException {		
	Token token=new Token();
	
	// Is ralasafe security enabled?
	boolean secured=RalasafeController.isSecured();
	
	if( secured ) {
		User currentUser=WebRalasafe.getCurrentUser( req );
		token.setCanAssignRoleToUser( Ralasafe.hasPrivilege( Privilege.ASSIGN_ROLE_TO_USER_ID, currentUser ) );
		token.setCanAdminRole( Ralasafe.hasPrivilege( Privilege.ROLE_ADMIN_ID, currentUser ) );
		token.setCanAdminPolicy( Ralasafe.hasPrivilege( Privilege.POLICY_ADMIN_ID, currentUser ) );
	}
	
	req.setAttribute( "token", token );
	WebUtil.forward( req, resp, "/ralasafe/main.jsp" );
}
 
Example 2
Project: alfresco-remote-api   File: BaseKerberosAuthenticationFilter.java   Source Code and License 9 votes vote down vote up
/**
 * The logon to start again
 *
 * @param context ServletContext
 * @param req HttpServletRequest
 * @param resp HttpServletResponse
 * @param ignoreFallback ignore fallback
 * @throws IOException
 */
private void logonStartAgain(ServletContext context, HttpServletRequest req, HttpServletResponse resp, boolean ignoreFallback) throws IOException
    {
    if (getLogger().isDebugEnabled())
        getLogger().debug("Issuing login challenge to browser.");
    // Force the logon to start again
    resp.setHeader("WWW-Authenticate", "Negotiate");
    
    if (!ignoreFallback && isFallbackEnabled())
    {
        includeFallbackAuth(context, req, resp);
    }
    
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    writeLoginPageLink(context, req, resp);
    resp.flushBuffer();
}
 
Example 3
Project: Guestbook9001   File: EditController.java   Source Code and License 7 votes vote down vote up
@GetMapping("/delete/{id}")
public String getDelete(HttpServletRequest request, HttpServletResponse response, @PathVariable long id,
						Model model) throws IOException {
	HttpSession session = request.getSession(true);
	Entry entry = getEntryDao().getEntry(id);

	if(entry == null) {
		response.sendError(HttpServletResponse.SC_NOT_FOUND);
		return null;
	}

	if(canEdit(session, entry)) {
		model.addAttribute("entry", entry);
		return "delete";
	}

	response.sendError(HttpServletResponse.SC_FORBIDDEN);
	return null;
}
 
Example 4
Project: loom   File: LoomServiceImpl.java   Source Code and License 7 votes vote down vote up
@Override
@RequestMapping(value = ApiConfig.ACTION_RESULTS_BASE + "/{actionResultId}", method = RequestMethod.GET,
        headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES})
@ResponseBody
public ActionResult getActionResult(@PathVariable final String actionResultId,
        @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId,
        final HttpServletResponse response) throws InvalidActionSpecificationException, NoSuchProviderException,
        NoSuchSessionException, NoSuchItemTypeException {
    if (rateLimiter.tryAcquire()) {
        if (actionResultId == null) {
            throw new BadRequestException("actionResultId cannot be null");
        }
        UUID uuid = UUID.fromString(actionResultId);
        Session session = modelValidator.validateSession(sessionId, response);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Lookup action result " + actionResultId + " for session " + sessionId);
        }
        synchronized (session) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Assigned session " + session.getId());
            }
            ActionResult actionResult = actionManager.getActionResult(session, uuid);
            return actionResult;
        }
    } else {
        throw new ApiThrottlingException("Exceeded max number of requests per second");
    }
}
 
Example 5
Project: OutsourcedProject   File: Excel.java   Source Code and License 7 votes vote down vote up
/**
 * 向客户端下载文件,弹出下载框.
 *
 * @param response(HttpServletResponse)
 * @param file(需要下载的文件)
 * @param isDel(下载完成后是否删除该文件)
 * @throws IOException
 */
public static void exportFile(HttpServletResponse response, File file, boolean isDel) throws IOException {
    OutputStream out = null;
    InputStream in = null;

    // 获得文件名
    String filename = URLEncoder.encode(file.getName(), "UTF-8");
    response.reset();
    // 定义输出类型(下载)
    response.setContentType("application/x-msdownload");
    response.setHeader("Location", filename);
    // 定义输出文件头
    response.setHeader("Content-Disposition", "attachment;filename=" + filename);
    out = response.getOutputStream();
    in = new FileInputStream(file.getPath());

    byte[] buffer = new byte[1024];
    int i = -1;
    while ((i = in.read(buffer)) != -1) {
        out.write(buffer, 0, i);
    }

    in.close();
    out.close();

    if (isDel) {
        //删除文件,删除前关闭所有的Stream.
        file.delete();
    }

}
 
Example 6
Project: uavstack   File: RewriteIvcResponseWrapper.java   Source Code and License 6 votes vote down vote up
public RewriteIvcResponseWrapper(HttpServletResponse response, String tag) {
    super(response);
    this.tag = tag;
    this.response = response;
    try {
        this.outputStream = response.getOutputStream();
        // 由于tomcat等实现类会记录是否调用了getOutputStream方法,故此处进行这种操作
        response.reset();
    }
    catch (IOException e) {
        // 出现异常时则将异常信息放入
        builder.append(e.toString());
    }
    this.rewriteOutStream = new RewriteIvcOutputStream(outputStream, response.getCharacterEncoding());
}
 
Example 7
Project: ssm-demo   File: UserController.java   Source Code and License 6 votes vote down vote up
/**
 * 修改密码
 *
 * @param user
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/modifyPassword")
public String modifyPassword(User user, HttpServletResponse response) throws Exception {
    String MD5pwd = MD5Util.MD5Encode(user.getPassword(), "UTF-8");
    user.setPassword(MD5pwd);
    int resultTotal = userService.updateUser(user);
    JSONObject result = new JSONObject();
    if (resultTotal > 0) {
        result.put("success", true);
    } else {
        result.put("success", false);
    }
    log.info("request: user/modifyPassword , user: " + user.toString());
    ResponseUtil.write(response, result);
    return null;
}
 
Example 8
Project: apache-tomcat-7.0.73-with-comment   File: TestCorsFilter.java   Source Code and License 6 votes vote down vote up
@Test
public void testCheckPreFlightRequestTypeOriginNotAllowed()
        throws ServletException, IOException {
    TesterHttpServletRequest request = new TesterHttpServletRequest();
    TesterHttpServletResponse response = new TesterHttpServletResponse();
    request.setHeader(CorsFilter.REQUEST_HEADER_ORIGIN,
            "www.ebay.com");
    request.setHeader(
            CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD,
            "PUT");
    request.setMethod("OPTIONS");
    CorsFilter corsFilter = new CorsFilter();
    corsFilter.init(TesterFilterConfigs
            .getSecureFilterConfig());
    corsFilter.doFilter(request, response, filterChain);
    Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN,
            response.getStatus());
}
 
Example 9
Project: NiuBi   File: HttpRequestTest.java   Source Code and License 6 votes vote down vote up
/**
 * Get header parameter values
 *
 * @throws Exception
 */
@Test
public void getMixQuotedParameters() throws Exception {
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      response.setStatus(HTTP_OK);
      response.setHeader("a", "value; b=c; d=\"e\"");
    }
  };
  HttpRequest request = get(url);
  assertTrue(request.ok());
  Map<String, String> params = request.parameters("a");
  assertNotNull(params);
  assertEquals(2, params.size());
  assertEquals("c", params.get("b"));
  assertEquals("e", params.get("d"));
}
 
Example 10
Project: springboot-shiro-cas-mybatis   File: AbstractManagementController.java   Source Code and License 6 votes vote down vote up
/**
 * Resolve exception.
 *
 * @param request the request
 * @param response the response
 * @param ex the exception
 * @return the model and view
 * @throws IOException the iO exception
 */
@ExceptionHandler
public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response,
                                     final Exception ex) throws IOException {

    logger.error(ex.getMessage(), ex);
    final String contentType = request.getHeader(AJAX_REQUEST_HEADER_NAME);
    if (contentType != null && contentType.equals(AJAX_REQUEST_HEADER_VALUE)) {
        logger.debug("Handling exception {} for ajax request indicated by header {}",
                ex.getClass().getName(), AJAX_REQUEST_HEADER_NAME);
        JsonViewUtils.renderException(ex, response);
        return null;
    } else {
        logger.trace("Unable to resolve exception {} for request. Ajax request header {} not found.",
                ex.getClass().getName(), AJAX_REQUEST_HEADER_NAME);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        final ModelAndView mv = new ModelAndView("errors");
        mv.addObject(ex);
        return mv;
    }
}
 
Example 11
Project: kaltura-ce-sakai-extension   File: FckKalturaSelectorController.java   Source Code and License 6 votes vote down vote up
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // create our model object
    Map<String,Object> model = new HashMap<String,Object>();

    // NOTE: we cannot get the current location from here -AZ
    //String locationId = external.getCurrentLocationId();
    String userId = external.getCurrentUserId();
    model.put("currentUserId", userId);
    model.put("isSuperUser", external.isUserAdmin(userId));

    /* Cannot show the special uploader here because we cannot get the current location
    String widgetPlayerUploadSpecialId = "";
    String widgetPlayerUploadSpecialKS = "";
    if (service.isKalturaUploadSpecial(userId, locationId)) {
        widgetPlayerUploadSpecialId = service.getKalturaWidgetId(Widget.UPLOADER_SPECIAL);
        widgetPlayerUploadSpecialKS = service.getKalturaClient(MediaService.KS_PERM_LIST).getSessionId();
    }
    model.put("uploadSpecialId", widgetPlayerUploadSpecialId);
    model.put("uploadSpecialKS", widgetPlayerUploadSpecialKS);
     */

    return new ModelAndView("fckEditorSelector", model);
}
 
Example 12
Project: graphouse   File: MonitoringServlet.java   Source Code and License 6 votes vote down vote up
private void ping(HttpServletResponse resp) throws IOException {
    if (allowColdRun || metricSearch.isMetricTreeLoaded()) {
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().print("0;OK");
        return;
    }

    resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    resp.getWriter().println("2;Metric tree not loaded ");
}
 
Example 13
Project: NiuBi   File: HttpRequestTest.java   Source Code and License 6 votes vote down vote up
/**
 * Verify GET with escaped query parameters
 *
 * @throws Exception
 */
@Test
public void getWithEscapedMappedQueryParams() throws Exception {
  Map<String, String> inputParams = new HashMap<String, String>();
  inputParams.put("name", "us er");
  inputParams.put("number", "100");
  final Map<String, String> outputParams = new HashMap<String, String>();
  final AtomicReference<String> method = new AtomicReference<String>();
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      method.set(request.getMethod());
      outputParams.put("name", request.getParameter("name"));
      outputParams.put("number", request.getParameter("number"));
      response.setStatus(HTTP_OK);
    }
  };
  HttpRequest request = get(url, inputParams, true);
  assertTrue(request.ok());
  assertEquals("GET", method.get());
  assertEquals("us er", outputParams.get("name"));
  assertEquals("100", outputParams.get("number"));
}
 
Example 14
Project: aceql-http   File: ExceptionReturner.java   Source Code and License 6 votes vote down vote up
/**
    * Clean return of Exception in JSon format & log Exception.
    * @param request 
    * @param response
    * @param out
    * @param exception
    */
   public static void logAndReturnException(HttpServletRequest request,
    HttpServletResponse response, PrintWriter out, Exception exception) {

try {
    JsonErrorReturn jsonErrorReturn = new JsonErrorReturn(response,
    	HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
    	JsonErrorReturn.ERROR_ACEQL_ERROR, exception.getMessage(),
    	ExceptionUtils.getStackTrace(exception));

    out.println(jsonErrorReturn.build());
    LoggerUtil.log(request, exception);
} catch (Exception e) {
    // Should never happen
    e.printStackTrace();
}

   }
 
Example 15
Project: ssm-demo   File: UserController.java   Source Code and License 6 votes vote down vote up
/**
 * 添加或修改管理员
 *
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/save")
public String save(User user, HttpServletResponse response) throws Exception {
    int resultTotal = 0;
    String MD5pwd = MD5Util.MD5Encode(user.getPassword(), "UTF-8");
    user.setPassword(MD5pwd);
    if (user.getId() == null) {
        resultTotal = userService.addUser(user);
    } else {
        resultTotal = userService.updateUser(user);
    }
    JSONObject result = new JSONObject();
    if (resultTotal > 0) {
        result.put("success", true);
    } else {
        result.put("success", false);
    }
    log.info("request: user/save , user: " + user.toString());
    ResponseUtil.write(response, result);
    return null;
}
 
Example 16
Project: dswork   File: APIController.java   Source Code and License 6 votes vote down vote up
/**
 * @note 获取指定用户的基本信息
 * @param userAccount 用户帐号
 * @return IUser
 */
@RequestMapping("/getUser")
public void getUser(HttpServletRequest request, HttpServletResponse response)
{
	MyRequest req = new MyRequest(request);
	String systemAlias = req.getString("name");
	String pwd = req.getString("pwd");
	String userAccount = req.getString("userAccount");
	try
	{
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = response.getWriter();
		if(isSystemCheck(systemAlias, pwd))
		{
			IUser m = service.getUserByAccount(userAccount);
			out.print(toJson(m));
		}
		out.print("");
	}
	catch(Exception ex)
	{
		ex.printStackTrace();
	}
}
 
Example 17
Project: uavstack   File: ServerSpanAdapter.java   Source Code and License 6 votes vote down vote up
/**
 * 根据HttpServletRequest获取指定格式的headers
 * 
 * @param request
 * @return
 */
private String getResponHeaders(HttpServletResponse response) {

    Map<String, String> result = new HashMap<String, String>();
    for (String key : response.getHeaderNames()) {
        result.put(key, response.getHeader(key));
    }
    return JSONHelper.toString(result);
}
 
Example 18
Project: oscm   File: IllegalRequestParameterFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (hasToBeFiltered(httpRequest)) {

        RequestWithCleanParameters cleanRequest = new RequestWithCleanParameters(
                httpRequest, ignorePatterns);

        cleanRequest.escapeAll(replaceMap);

        chain.doFilter(cleanRequest, httpResponse);

    } else {
        chain.doFilter(httpRequest, httpResponse);
    }

}
 
Example 19
Project: uavstack   File: JEEServiceRunGlobalFilterHandler.java   Source Code and License 6 votes vote down vote up
@Override
protected void doResponse(HttpServletRequest request, HttpServletResponse response, InterceptContext ic) {

    Map<String, Object> params = new HashMap<String, Object>();

    params.put(CaptureConstants.INFO_APPSERVER_CONNECTOR_REQUEST_URL, request.getRequestURL().toString());
    params.put(CaptureConstants.INFO_APPSERVER_CONNECTOR_CONTEXT, getReqContextPath(request));
    params.put(CaptureConstants.INFO_APPSERVER_CONNECTOR_CONTEXT_REALPATH, getReqRealPath(request));
    params.put(CaptureConstants.INFO_APPSERVER_CONNECTOR_RESPONSECODE, getRespRetStatus(response));

    Object args[] = { request, response };

    // invoke chain
    UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "runCap",
            InvokeChainConstants.CHAIN_APP_SERVICE, InvokeChainConstants.CapturePhase.DOCAP, params,
            ServerSpanAdapter.class, args);

}
 
Example 20
Project: lams   File: ErrorReportValve.java   Source Code and License 6 votes vote down vote up
/**
 * Invoke the next Valve in the sequence. When the invoke returns, check
 * the response state, and output an error report is necessary.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response)
    throws IOException, ServletException {

    // Perform the request
    getNext().invoke(request, response);

    Throwable throwable =
        (Throwable) request.getAttribute(Globals.EXCEPTION_ATTR);

    if (response.isCommitted()) {
        return;
    }

    if (throwable != null) {

        // The response is an error
        response.setError();

        // Reset the response (if possible)
        try {
            response.reset();
        } catch (IllegalStateException e) {
            ;
        }

        response.sendError
            (HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    }

    response.setSuspended(false);

    try {
        report(request, response, throwable);
    } catch (Throwable tt) {
        ;
    }

}
 
Example 21
Project: SpringTutorial   File: UserCards.java   Source Code and License 6 votes vote down vote up
protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	PrintWriter out = response.getWriter();
	out.println("<html>");
	out.println("<head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>");
	out.println("<title>Your Cards</title>");
	out.println("</head>");
	out.println("<body>");
	out.println("<h3>Your Cards List</h3>");
	out.println("<h3>Card A(Balance -234.00)</h3>");
	out.println("<h3>Card B(Balance 0.00)</h3>");
	out.println("<br>");
	out.println("<a href=\"/ServletSample/UserAccounts\"> My Account</a>");
	out.println("<br><a href=\"/ServletSample/BankHomePage\">Click here to go back to homepage</a>");
	out.println("</body></html>");
}
 
Example 22
Project: airsonic   File: PlaylistService.java   Source Code and License 5 votes vote down vote up
public int createPlaylistForPlayQueue() {
    HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
    HttpServletResponse response = WebContextFactory.get().getHttpServletResponse();
    Player player = playerService.getPlayer(request, response);
    Locale locale = localeResolver.resolveLocale(request);
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, locale);

    Date now = new Date();
    Playlist playlist = new Playlist();
    playlist.setUsername(securityService.getCurrentUsername(request));
    playlist.setCreated(now);
    playlist.setChanged(now);
    playlist.setShared(false);
    playlist.setName(dateFormat.format(now));

    playlistService.createPlaylist(playlist);
    playlistService.setFilesInPlaylist(playlist.getId(), player.getPlayQueue().getFiles());

    return playlist.getId();
}
 
Example 23
Project: easycms   File: TableServlet.java   Source Code and License 5 votes vote down vote up
private void saveColumn(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
	Column column = new Column();
	String id = request.getParameter("id");
	if (StringUtils.isNotEmpty(id)) {
		column.setId(Integer.parseInt(id));
	}
	String modelId = request.getParameter("modelId");
	column.setModelId(Integer.parseInt(modelId));
	
	String name = request.getParameter("name");
	column.setName(name);
	String type = request.getParameter("type");
	column.setType(type);
	String mappingData = request.getParameter("mappingData");
	column.setMappingData(mappingData);
	
	String sql = request.getParameter("sql");
	column.setSql(sql);
	
	String seq = request.getParameter("seq");
	if (StringUtils.isNumeric(seq)) {
		column.setSeq(Integer.parseInt(seq));
	}
	String width = request.getParameter("width");
	if (StringUtils.isNumeric(width)) {
		column.setWidth(Integer.parseInt(width));
	}
	String allowBlank = request.getParameter("allowBlank");
	column.setAllowBlank(allowBlank);
	String listShow = request.getParameter("listShow");
	column.setListShow(listShow);
	String remark = request.getParameter("remark");
	column.setRemark(remark);
	
	columnService.save(column);
	this.write(new Ajax(true, "保存成功"), response);
}
 
Example 24
Project: dubbo2   File: HttpProtocol.java   Source Code and License 5 votes vote down vote up
public void handle(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String uri = request.getRequestURI();
    HttpInvokerServiceExporter skeleton = skeletonMap.get(uri);
    if (! request.getMethod().equalsIgnoreCase("POST")) {
        response.setStatus(500);
    } else {
        RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
        try {
            skeleton.handleRequest(request, response);
        } catch (Throwable e) {
            throw new ServletException(e);
        }
    }
}
 
Example 25
Project: lams   File: AuthoringAction.java   Source Code and License 5 votes vote down vote up
public ActionForward loadHeadingForm(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) {

String sessionMapID = WebUtil.readStrParam(request, "sessionMapID");
Integer headingIndex = WebUtil.readIntParam(request, "headingIndex", true);

AuthoringForm authForm = ((AuthoringForm) form);

if (headingIndex == null) {
    headingIndex = -1;
}

authForm.setHeadingIndex(headingIndex);
authForm.setSessionMapID(sessionMapID);

return mapping.findForward("heading_form");
   }
 
Example 26
Project: openNaEF   File: KeseranApi.java   Source Code and License 5 votes vote down vote up
@GET
@Path("/pseudo-wire")
@Produces(MediaType.APPLICATION_JSON)
public String 時間を指定してPWを取得(
        @Context HttpHeaders header,
        @Context HttpServletResponse response,
        @QueryParam("time") String time,
        @QueryParam("version") String version
) throws RemoteException {
    response.setHeader("Access-Control-Allow-Origin", "*");
    List<PasaranPOJO> pojos = PseudoWirePOJOUtil.getPseudoWire(time, version);
    return json.format(pojos);
}
 
Example 27
Project: kettle_support_kettle8.0   File: UserController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = ACTION_UPDATE, method = RequestMethod.GET)
public String edit(HttpServletRequest request, HttpServletResponse response) {
	Iterator<?> it = request.getParameterMap().entrySet().iterator();
	User entity = new User();
	while (it.hasNext()) {
		Map.Entry<?, ?> ent = (Entry<?, ?>) it.next();
		entity.setValue((String) ent.getKey(),
				((String[]) ent.getValue())[0]);
	}
	entity = (User) service.iUserService.select(entity);
	request.setAttribute(ID, entity.getId());
	request.setAttribute(ENTITY, entity);
	return VIEW_SYSTEM + VIEW_USER + PAGE_UPDATE;
}
 
Example 28
Project: zhkuas_ssm_maven   File: AdminSecurityInterceptor.java   Source Code and License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
	HttpSession session = request.getSession(true);  
       // 从session 里面获取用户名的信息  
       Object obj = session.getAttribute(Constants.SessionKey.ADMIN_USER.toString());  
       // 判断如果没有取到用户信息,就跳转到登陆页面,提示用户进行登陆  
       if (obj == null || "".equals(obj.toString())) {  
       	response.sendRedirect(request.getContextPath()+"/admin/"+LOGIN_URL);  
       	return false;
       }  
       return true;  
}
 
Example 29
Project: cas-5.1.0   File: SendTicketGrantingTicketAction.java   Source Code and License 5 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final String ticketGrantingTicketValueFromCookie = (String) context.getFlowScope().get("ticketGrantingTicketId");
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

    if (StringUtils.isBlank(ticketGrantingTicketId)) {
        LOGGER.debug("No ticket-granting ticket is found in the context.");
        return success();
    }

    if (WebUtils.isAuthenticatingAtPublicWorkstation(context)) {
        LOGGER.info("Authentication is at a public workstation. SSO cookie will not be generated. Requests will be challenged for authentication.");
    } else if (!this.createSsoSessionCookieOnRenewAuthentications && isAuthenticationRenewed(context)) {
        LOGGER.info("Authentication session is renewed but CAS is not configured to create the SSO session. "
                + "SSO cookie will not be generated. Subsequent requests will be challenged for credentials.");
    } else {
        LOGGER.debug("Setting TGC for current session linked to [{}].", ticketGrantingTicketId);
        this.ticketGrantingTicketCookieGenerator.addCookie(request, response, ticketGrantingTicketId);
    }

    if (ticketGrantingTicketValueFromCookie != null && !ticketGrantingTicketId.equals(ticketGrantingTicketValueFromCookie)) {
        LOGGER.debug("Ticket-granting ticket from TGC does not match the ticket-granting ticket from context");
        this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketValueFromCookie);
    }

    return success();
}
 
Example 30
Project: lams   File: LearningAction.java   Source Code and License 5 votes vote down vote up
public ActionForward submitReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) {

// save the reflection entry and call the notebook.

LearningForm lrnForm = (LearningForm) form;

BbbUser user = getCurrentUser(lrnForm.getToolSessionID());
Long toolSessionID = user.getBbbSession().getSessionId();
Integer userID = user.getUserId().intValue();

// check for existing notebook entry
NotebookEntry entry = bbbService.getNotebookEntry(user.getNotebookEntryUID());

if (entry == null) {
    // create new entry
    Long entryUID = bbbService.createNotebookEntry(toolSessionID, CoreNotebookConstants.NOTEBOOK_TOOL,
	    Constants.TOOL_SIGNATURE, userID, lrnForm.getEntryText());
    user.setNotebookEntryUID(entryUID);
    bbbService.saveOrUpdateBbbUser(user);
} else {
    // update existing entry
    entry.setEntry(lrnForm.getEntryText());
    entry.setLastModified(new Date());
    bbbService.updateNotebookEntry(entry);
}

return finishActivity(mapping, form, request, response);
   }
 
Example 31
Project: apache-tomcat-7.0.73-with-comment   File: TestSSOnonLoginAndBasicAuthenticator.java   Source Code and License 5 votes vote down vote up
@Test
public void testBasicExpiredAcceptProtectedWithCookies() throws Exception {

    setRapidSessionTimeoutDetection();

    // begin with a repeat of testBasicLoginAcceptProtectedWithCookies
    doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED,
            NO_CREDENTIALS, USE_COOKIES,
            HttpServletResponse.SC_UNAUTHORIZED);
    doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED,
            GOOD_CREDENTIALS, USE_COOKIES,
            HttpServletResponse.SC_OK);
    doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED,
                   USE_COOKIES, HttpServletResponse.SC_OK);

    // wait long enough for the BASIC session to expire,
    // but not long enough for the NonLogin session expiry.
    doImminentSessionTimeout(basicContext);

    // this successful NonLogin access should replenish the
    // the individual session expiry time and keep the SSO session alive
    doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED,
                   USE_COOKIES, HttpServletResponse.SC_OK);

    // wait long enough for the NonLogin session to expire,
    // which will also tear down the SSO session at the same time.
    doImminentSessionTimeout(nonloginContext);

    doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, USE_COOKIES,
            HttpServletResponse.SC_FORBIDDEN);
    doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED,
            NO_CREDENTIALS, USE_COOKIES,
            HttpServletResponse.SC_UNAUTHORIZED);

}
 
Example 32
Project: central-medic-center   File: PatientServlet.java   Source Code and License 5 votes vote down vote up
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	
	try {
		session = request.getSession();
		if (session.isNew()){
			redirectToLogin(request, response);
			 }
		else{
		
		int personId = (int) session.getAttribute("UserID");
		// get patient details
		DatabaseHelper databaseHelper = new DatabaseHelper();
		Patient patient = databaseHelper.getPatient(personId);
		DashBoard dashBoard = new DashBoard(databaseHelper.getAppointmentCount(personId,"patientId"), 
				DashUtils.getBMI(patient.getHeight(), patient.getWeight()),DashUtils.getMedicineCount(personId),DashUtils.getProfileRating(personId, 1));
		ArrayList<ArrayList<Appointment>> appointments = databaseHelper.getAppointments(personId, "patientId");
		if (patient == null || appointments == null || dashBoard == null) {
			// redirect to login
			redirectToLogin(request, response);
			return;
		}
		// redirect to person dashboard
		RequestDispatcher rs = request.getRequestDispatcher("patient.jsp");
		request.setAttribute("patient", patient);
		request.setAttribute("appointments", appointments);
		request.setAttribute("dashBoard", dashBoard);
		rs.forward(request, response);
		return;
		}
	} catch (Exception e) {
		// redirect to login
		redirectToLogin(request, response);
	}
	}
 
Example 33
Project: omero-ms-queue   File: FileStreamer.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new instance to stream the specified file.
 * @param content path to the file to stream.
 * @param contentType the content type to set in the response.
 * @param cacheStrategy sets cache directives in the response.
 * @throws NullPointerException if any argument is {@code null}.
 */
public FileStreamer(Path content, MediaType contentType, 
                    Consumer<HttpServletResponse> cacheStrategy) {
    requireNonNull(content, "content");
    requireNonNull(contentType, "contentType");
    requireNonNull(cacheStrategy, "cacheStrategy");
    
    this.content = content;
    this.contentType = contentType;
    this.cacheStrategy = cacheStrategy;
}
 
Example 34
Project: lams   File: IndexAction.java   Source Code and License 5 votes vote down vote up
/**
    * Saves to DB last visited organisation. It's required for displaying some org on main.jsp next time user logs in.
    */
   public ActionForward storeLastVisitedOrganisation(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse res) throws IOException, ServletException {
getUserManagementService();
Integer lastVisitedOrganisationId = WebUtil.readIntParam(request, "orgId", false);

//saves to DB last visited organisation
if (lastVisitedOrganisationId != null) {
    User user = userManagementService.getUserByLogin(request.getRemoteUser());
    user.setLastVisitedOrganisationId(lastVisitedOrganisationId);
    userManagementService.saveUser(user);
}

return null;
   }
 
Example 35
Project: apache-tomcat-7.0.73-with-comment   File: TestPersistentManagerIntegration.java   Source Code and License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    boolean createSession = !Boolean.parseBoolean(req
                    .getParameter("no_create_session"));
    HttpSession session = req.getSession(createSession);
    if (session == null) {
        resp.getWriter().print("NO_SESSION");
    } else {
        String id = session.getId();
        resp.getWriter().print(id);
    }
}
 
Example 36
Project: spring-boot-start-current   File: JwtAuthenticationEntryPoint.java   Source Code and License 5 votes vote down vote up
@Override
public void commence ( HttpServletRequest request ,
					   HttpServletResponse response ,
					   AuthenticationException authException ) throws IOException {
	response.setHeader( "Content-type" , MediaType.APPLICATION_JSON_UTF8_VALUE );
	response.setCharacterEncoding( StandardCharsets.UTF_8.displayName() );
	try ( PrintWriter out = response.getWriter() ) {
		out.print( JsonUtils.toCustomizationJson( ResponseEntityPro.unauthorized( "未经授权:身份验证令牌丢失或无效。" ) ) );
	}
}
 
Example 37
Project: csap-core   File: HostRequests.java   Source Code and License 5 votes vote down vote up
private void runFsScript ( int numGb, String targetFs, HttpServletResponse response )
		throws IOException {

	String psResult;
	response.getWriter()
		.println(
			"==  targetFs: " + targetFs + " Size of test file (Gb) :" + numGb );
	response.getWriter()
		.flush();
	List<String> parmList = Arrays.asList( "bash", "-c", "checkFsThroughput.sh " + numGb + " "
			+ targetFs );
	psResult = osCommandRunner
		.executeString( parmList, new File( "." ), null, null, 600, 10, null );

	auditRecord( "checkFsThroughput", psResult );

	logger.debug( "psResult: {} ", psResult );
	response.getWriter()
		.println( psResult );

	response.getWriter()
		.flush();
}
 
Example 38
Project: Mastering-Spring-5.0   File: HandlerTimeLoggingInterceptor.java   Source Code and License 5 votes vote down vote up
@Override
public void afterCompletion(HttpServletRequest request,
		HttpServletResponse response, Object handler, Exception ex)
		throws Exception {
	long startTime = (Long) request.getAttribute("startTime");
	long endTime = (Long) request.getAttribute("endTime");
	logger.info("Time Spent in Handler in ms : " + (endTime - startTime));
}
 
Example 39
Project: osc-core   File: UiServletContext.java   Source Code and License 5 votes vote down vote up
@Override
public boolean handleSecurity(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    final String resource = request.getRequestURI();
    if (!resource.endsWith("/")) {
        URI resolve = this.base.resolve(OSC_RESOURCE_PREFIX.substring(1) + resource);
        if (new File(resolve).isDirectory()) {
            response.sendRedirect(resource + "/");
            return false;
        }
    }
    return true;
}
 
Example 40
Project: attendance   File: GetJsonData.java   Source Code and License 5 votes vote down vote up
@RequestMapping("getClientLinkManInfo.do")
public void getLinkManById(HttpServletRequest request,HttpServletResponse response){
	int id=Integer.parseInt(request.getParameter("id"));
	LinkMan linkman=linkmanservice.queryLinkManById(id);	     	
	try {
		response.getWriter().print(JSON.toJSON(linkman));
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 41
Project: easyweb   File: OssController.java   Source Code and License 5 votes vote down vote up
/**
     * 登录
     * @return
     */
    @GetMapping("/login")
    @ApiOperation(value = "登录界面")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String principal = UserUtils.getPrincipal();

//		// 默认页签模式
//		String tabmode = CookieUtils.getCookie(request, "tabmode");
//		if (tabmode == null){
//			CookieUtils.setCookie(response, "tabmode", "1");
//		}
//
//        if (logger.isDebugEnabled()){
//            logger.debug("login, active session size: {}", sessionDAO.getActiveSessions(false).size());
//        }

        // 如果已登录,再次访问主页,则退出原账号。
        if (Global.TRUE.equals(Global.getInstance().getConfig("notAllowRefreshIndex"))){
            CookieUtils.setCookie(response, "LOGINED", "false");
        }

        // 如果已经登录,则跳转到管理首页
        if(StringUtils.isNotEmpty(principal)){
            return "redirect:/admin/index";
        }
        return "login";
    }
 
Example 42
Project: automat   File: MaliciousRequestInterceptor.java   Source Code and License 5 votes vote down vote up
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
	response.setHeader("Access-Control-Allow-Origin", "*");
	response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
	response.setHeader("Access-Control-Allow-Headers",
			"x-requested-with,Access-Control-Allow-Origin,EX-SysAuthToken,EX-JSESSIONID");

	String url = request.getServletPath();
	if (url.endsWith("/unauthorized") || url.endsWith("/forbidden")) {
		return super.preHandle(request, response, handler);
	}
	HttpSession session = request.getSession();
	String preRequest = (String) session.getAttribute(Constants.PREREQUEST);
	Long preRequestTime = (Long) session.getAttribute(Constants.PREREQUEST_TIME);
	if (preRequestTime != null && preRequest != null) { // 过滤频繁操作
		if ((url.equals(preRequest) || allRequest)
				&& System.currentTimeMillis() - preRequestTime < minRequestIntervalTime) {
			Integer maliciousRequestTimes = (Integer) session.getAttribute(Constants.MALICIOUS_REQUEST_TIMES);
			if (maliciousRequestTimes == null) {
				maliciousRequestTimes = 1;
			} else {
				maliciousRequestTimes++;
			}
			session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, maliciousRequestTimes);
			if (maliciousRequestTimes > maxMaliciousTimes) {
				response.setStatus(HttpCode.MULTI_STATUS.value());
				logger.warn("To intercept a malicious request : {}", url);
				return false;
			}
		} else {
			session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, 0);
		}
	}
	session.setAttribute(Constants.PREREQUEST, url);
	session.setAttribute(Constants.PREREQUEST_TIME, System.currentTimeMillis());
	return super.preHandle(request, response, handler);
}
 
Example 43
Project: LojaDeInstrumentosMusicais   File: ListagemDeCarrinhoServlet.java   Source Code and License 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServicoCarrinho sc = new ServicoCarrinho();
    ServicoItemCarrinho sic = new ServicoItemCarrinho();
    ServicoProduto sp = new ServicoProduto();
    ServicoCliente scli = new ServicoCliente();
    
    Carrinho carrinho = new Carrinho();
    ItemCarrinho itemcarrinho = new ItemCarrinho();
    
    List<ItemCarrinho> listaitens= new ArrayList<ItemCarrinho>();
    List<Produto> listaprodutos = new ArrayList<Produto>();
    List<Cliente> listaclientes = new ArrayList<Cliente>();
    
    //Criação se sessão para retorno em tela
    HttpSession sessao = request.getSession();
    
    String codigoCarrinho = request.getParameter("codigocarrinho");
    String codigoempresa = (String) sessao.getAttribute("Empresa");
    
    try {
        carrinho = sc.retornaCarrinho(Integer.parseInt(codigoCarrinho));
        listaitens = sic.listarItensCarrinho(Integer.parseInt(codigoCarrinho));
        listaprodutos = sp.listarProdutos(Integer.parseInt(codigoempresa));
        listaclientes =scli.listarClientes(Integer.parseInt(codigoempresa));
    } catch (Exception e) {
    }
    
    sessao.setAttribute("cabecalhocarrinho", carrinho);
    sessao.setAttribute("itenscarrinho", listaitens);
    sessao.setAttribute("listaprodutos", listaprodutos);
    sessao.setAttribute("listaclientes", listaclientes);
    
    //Remove venda feita anteriormente
    sessao.removeAttribute("venda");
    response.sendRedirect(request.getContextPath() + "/finalizarVenda.jsp");   
    
    
}
 
Example 44
Project: lams   File: WebSocketServlet.java   Source Code and License 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {

    final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(req, resp, peerConnections);
    Handshake handshaker = null;
    for (Handshake method : handshakes) {
        if (method.matches(facade)) {
            handshaker = method;
            break;
        }
    }

    if (handshaker == null) {
        UndertowLogger.REQUEST_LOGGER.debug("Could not find hand shaker for web socket request");
        resp.sendError(StatusCodes.BAD_REQUEST);
        return;
    }
    final Handshake selected = handshaker;
    facade.upgradeChannel(new HttpUpgradeListener() {
        @Override
        public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
            WebSocketChannel channel = selected.createChannel(facade, streamConnection, facade.getBufferPool());
            peerConnections.add(channel);
            callback.onConnect(facade, channel);
        }
    });
    handshaker.handshake(facade);
}
 
Example 45
Project: redesocial   File: EstadoControle.java   Source Code and License 5 votes vote down vote up
/**
 * Exclui um estado no banco de dados
 * @param request
 * @param response
 * @throws Exception
 */
private void excluir(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        Integer id = Integer.parseInt(request.getParameter("id"));

        EstadoBO bo = new EstadoBO();
        bo.excluir(id);

        request.setAttribute("mensagem", "Excluído com sucesso");
    } catch (Exception ex){
        request.setAttribute("erro", ex.getMessage());
    }

    this.listar(request, response);
}
 
Example 46
Project: lams   File: MonitoringAction.java   Source Code and License 5 votes vote down vote up
/**
    * main content/question content management and workflow logic
    */
   @Override
   public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {
VoteUtils.cleanUpUserExceptions(request);
return null;
   }
 
Example 47
Project: apache-tomcat-7.0.73-with-comment   File: TestSwallowAbortedUploads.java   Source Code and License 5 votes vote down vote up
@Test
public void testAbortedPOST413NoSwallow() {
    log.info("Aborted (413), swallow disabled");
    AbortedPOSTClient client = new AbortedPOSTClient();
    Exception ex = doAbortedPOSTTest(client, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, false);
    assertTrue("Limited upload with swallow disabled does not generate client exception",
               ex != null && ex instanceof java.net.SocketException);
    client.reset();
}
 
Example 48
Project: lams   File: ServletConfidentialityConstraintHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    final AuthorizationManager authorizationManager = servletRequestContext.getDeployment().getDeploymentInfo().getAuthorizationManager();

    TransportGuaranteeType connectionGuarantee = servletRequestContext.getOriginalRequest().isSecure() ? TransportGuaranteeType.CONFIDENTIAL : TransportGuaranteeType.NONE;
    TransportGuaranteeType transportGuarantee = authorizationManager.transportGuarantee(connectionGuarantee,
            servletRequestContext.getTransportGuarenteeType(), servletRequestContext.getOriginalRequest());
    servletRequestContext.setTransportGuarenteeType(transportGuarantee);

    if (TransportGuaranteeType.REJECTED == transportGuarantee) {
        HttpServletResponse response = (HttpServletResponse) servletRequestContext.getServletResponse();
        response.sendError(StatusCodes.FORBIDDEN);
        return;
    }
    super.handleRequest(exchange);
}
 
Example 49
Project: JAVA-   File: CsrfFilter.java   Source Code and License 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	try {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		// 获取请求url地址
		String url = req.getRequestURL().toString();
		String referurl = req.getHeader("Referer");
		if (isWhiteReq(referurl)) {
			chain.doFilter(request, response);
		} else {
			req.getRequestDispatcher("/").forward(req, res);

			// 记录跨站请求日志
			String log = "";
			String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String clientIp = WebUtil.getHost(req);

			log = "跨站请求---->>>" + clientIp + "||" + date + "||" + referurl + "||" + url;
			logger.warn(log);
			return;
		}

	} catch (Exception e) {
		logger.error("doFilter", e);
	}

}
 
Example 50
Project: configx   File: LoginInterceptor.java   Source Code and License 5 votes vote down vote up
/**
 * 未登录
 *
 * @param email
 * @param request
 * @param response
 */
private void onNotLoggedIn(String email, HttpServletRequest request, HttpServletResponse response) {
    try {
        String back = request.getRequestURI();
        if (StringUtils.isEmpty(back) || back.contains("/user/logout")) {
            response.sendRedirect("/user/login");
        } else {
            response.sendRedirect("/user/login?back=" + back);
        }
    } catch (Exception e) {

    }
}
 
Example 51
Project: solo-spring   File: PreferenceConsole.java   Source Code and License 5 votes vote down vote up
/**
 * Gets signs.
 *
 * <p>
 * Renders the response with a json object, for example,
 * 
 * <pre>
 * {
 *     "sc": boolean,
 *     "signs": [{
 *         "oId": "",
 *         "signHTML": ""
 *      }, ...]
 * }
 * </pre>
 * </p>
 *
 * @param request
 *            the specified http servlet request
 * @param response
 *            the specified http servlet response
 * @param context
 *            the specified http request context
 * @throws Exception
 *             exception
 */
@RequestMapping(value = "/console/signs/", method = RequestMethod.GET)
public void getSigns(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
	if (!userQueryService.isLoggedIn(request, response)) {
		response.sendError(HttpServletResponse.SC_FORBIDDEN);
		return;
	}

	final JSONRenderer renderer = new JSONRenderer();

	try {
		final JSONObject preference = preferenceQueryService.getPreference();

		final JSONArray signs = new JSONArray();

		final JSONArray allSigns = // includes the empty sign(id=0)
				new JSONArray(preference.getString(Option.ID_C_SIGNS));

		for (int i = 1; i < allSigns.length(); i++) { // excludes the empty
														// sign
			signs.put(allSigns.getJSONObject(i));
		}

		final JSONObject ret = new JSONObject();

		renderer.setJSONObject(ret);

		ret.put(Sign.SIGNS, signs);
		ret.put(Keys.STATUS_CODE, true);
	} catch (final Exception e) {
		logger.error(e.getMessage(), e);

		final JSONObject jsonObject = QueryResults.defaultResult();

		renderer.setJSONObject(jsonObject);
		jsonObject.put(Keys.MSG, langPropsService.get("getFailLabel"));
	}
	renderer.render(request, response);
}
 
Example 52
Project: parabuild-ci   File: FakeHttpServletResponse.java   Source Code and License 5 votes vote down vote up
public void reset()
{
    resetBuffer();

    characterEncoding = null;
    contentLength = 0;
    contentType = null;
    locale = null;
    cookies.clear();
    headers.clear();
    status = HttpServletResponse.SC_OK;
    errorMessage = null;
}
 
Example 53
Project: theLXGweb   File: UrlAuthenticationSuccessHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
                                    HttpServletResponse response, Authentication authentication)
  throws IOException {
  
    handle(request, response, authentication);
    clearAuthenticationAttributes(request);
}
 
Example 54
Project: springMvc4.x-project   File: DemoInterceptor.java   Source Code and License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, //②
		HttpServletResponse response, Object handler) throws Exception {
	long startTime = System.currentTimeMillis();
	request.setAttribute("startTime", startTime);
	return true;
}
 
Example 55
Project: kettle_support_kettle8.0   File: QuartzController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = ACTION_TREE, method = RequestMethod.GET)
public String eTree(HttpServletRequest request, HttpServletResponse response) {
	URL base = getClass().getClassLoader().getResource("");
	String basePath = base.getFile();
	String jobPackage = basePath
			+ Constant.EXEC_PATH.replaceAll("\\.", "/");
	listClazz(jobPackage);
	request.setAttribute(ENTITY, jobClassesMap);
	return VIEW_WIDGET + VIEW_QUARTZ + PAGE_TREE;
}
 
Example 56
Project: apache-tomcat-7.0.73-with-comment   File: TestRequest.java   Source Code and License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/plain");
    PrintWriter pw = resp.getWriter();
    pw.print("QueryString=" + req.getQueryString());
}
 
Example 57
Project: oauth2-shiro-redis   File: OAuthShiroHandlerExceptionResolver.java   Source Code and License 5 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    if (ex instanceof UnauthorizedException) {
        handleUnauthorizedException(response, ex);
    } else if (ex instanceof AuthorizationException) {
        handleUnauthorizedException(response, ex);
    }
    //more

    return null;
}
 
Example 58
Project: CommonInformationSpace   File: SimpleCORSFilter.java   Source Code and License 5 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	HttpServletResponse response = (HttpServletResponse) res;
	response.setHeader("Access-Control-Allow-Origin", "*");
	response.setHeader("Access-Control-Allow-Methods", "POST, PATCH, GET, OPTIONS, DELETE, PUT");
	response.setHeader("Access-Control-Max-Age", "3600");
	response.setHeader("Access-Control-Allow-Headers", "Content-Type, cache-control, x-requested-with");
	response.setHeader("Access-Control-Expose-Headers","Location");
	response.setHeader("cache-control","no-store");
	chain.doFilter(req, res);
}
 
Example 59
Project: bootstrap   File: BackendProxyServletTest.java   Source Code and License 5 votes vote down vote up
@Test
public void onProxyResponseFailureNotClosable() throws IOException, ServletException {
	init();
	final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
	final ServletOutputStream os = Mockito.mock(ServletOutputStream.class);
	Mockito.doThrow(new IOException()).when(os).write(ArgumentMatchers.any(byte[].class));
	Mockito.when(response.getOutputStream()).thenReturn(os);
	final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
	final AsyncContext asyncContext = Mockito.mock(AsyncContext.class);
	Mockito.when(request.getAsyncContext()).thenReturn(asyncContext);
	servlet.onProxyResponseFailure(request, response, null, new Exception());
}
 
Example 60
Project: cas-5.1.0   File: SamlProfileSaml2ResponseBuilder.java   Source Code and License 5 votes vote down vote up
@Override
protected Response buildResponse(final Assertion assertion,
                                 final org.jasig.cas.client.validation.Assertion casAssertion,
                                 final AuthnRequest authnRequest,
                                 final SamlRegisteredService service,
                                 final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                                 final HttpServletRequest request,
                                 final HttpServletResponse response,
                                 final String binding) throws SamlException {
    final String id = '_' + String.valueOf(Math.abs(new SecureRandom().nextLong()));
    Response samlResponse = newResponse(id, ZonedDateTime.now(ZoneOffset.UTC), authnRequest.getID(), null);
    samlResponse.setVersion(SAMLVersion.VERSION_20);
    samlResponse.setIssuer(buildEntityIssuer());
    samlResponse.setConsent(RequestAbstractType.UNSPECIFIED_CONSENT);

    final SAMLObject finalAssertion = encryptAssertion(assertion, request, response, service, adaptor);

    if (finalAssertion instanceof EncryptedAssertion) {
        LOGGER.debug("Built assertion is encrypted, so the response will add it to the encrypted assertions collection");
        samlResponse.getEncryptedAssertions().add(EncryptedAssertion.class.cast(finalAssertion));
    } else {
        LOGGER.debug("Built assertion is not encrypted, so the response will add it to the assertions collection");
        samlResponse.getAssertions().add(Assertion.class.cast(finalAssertion));
    }

    final Status status = newStatus(StatusCode.SUCCESS, StatusCode.SUCCESS);
    samlResponse.setStatus(status);

    SamlUtils.logSamlObject(this.configBean, samlResponse);

    if (service.isSignResponses()) {
        LOGGER.debug("SAML entity id [{}] indicates that SAML responses should be signed", adaptor.getEntityId());
        samlResponse = this.samlObjectSigner.encode(samlResponse, service, adaptor, 
                response, request, binding);
    }

    return samlResponse;
}