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   View source code 9 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   View source code 8 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: aceql-http   File: ExceptionReturner.java   View source code 7 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 4
Project: airsonic   File: PlaylistService.java   View source code 6 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 5
Project: lams   File: AuthoringAction.java   View source code 6 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 6
Project: uavstack   File: RewriteIvcResponseWrapper.java   View source code 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   View source code 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: Guestbook9001   File: EditController.java   View source code 6 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 9
Project: loom   File: LoomServiceImpl.java   View source code 6 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 10
Project: apache-tomcat-7.0.73-with-comment   File: TestCorsFilter.java   View source code 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 11
Project: NiuBi   File: HttpRequestTest.java   View source code 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 12
Project: springboot-shiro-cas-mybatis   File: AbstractManagementController.java   View source code 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 13
Project: csap-core   File: HostRequests.java   View source code 6 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 14
Project: kaltura-ce-sakai-extension   File: FckKalturaSelectorController.java   View source code 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 15
Project: graphouse   File: MonitoringServlet.java   View source code 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 16
Project: NiuBi   File: HttpRequestTest.java   View source code 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 17
Project: OutsourcedProject   File: Excel.java   View source code 6 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 18
Project: ssm-demo   File: UserController.java   View source code 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 19
Project: dswork   File: APIController.java   View source code 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 20
Project: uavstack   File: ServerSpanAdapter.java   View source code 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 21
Project: oscm   File: IllegalRequestParameterFilter.java   View source code 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 22
Project: uavstack   File: JEEServiceRunGlobalFilterHandler.java   View source code 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 23
Project: lams   File: ErrorReportValve.java   View source code 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 24
Project: SpringTutorial   File: UserCards.java   View source code 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 25
Project: cas-5.1.0   File: FlowExecutionExceptionResolver.java   View source code 5 votes vote down vote up
@Override
public ModelAndView resolveException(final HttpServletRequest request,
    final HttpServletResponse response, final Object handler,
    final Exception exception) {

    /*
     * Since FlowExecutionRepositoryException is a common ancestor to these exceptions and other
     * error cases we would likely want to hide from the user, it seems reasonable to check for
     * FlowExecutionRepositoryException.
     *
     * BadlyFormattedFlowExecutionKeyException is specifically ignored by this handler
     * because redirecting to the requested URI with this exception may cause an infinite
     * redirect loop (i.e. when invalid "execution" parameter exists as part of the query string
     */
    if (!(exception instanceof FlowExecutionRepositoryException)
          || exception instanceof BadlyFormattedFlowExecutionKeyException) {
        LOGGER.debug("Ignoring the received exception due to a type mismatch", exception);
        return null;
    }

    final String urlToRedirectTo = request.getRequestURI()
            + (request.getQueryString() != null ? '?'
            + request.getQueryString() : StringUtils.EMPTY);

    LOGGER.debug("Error getting flow information for URL [{}]", urlToRedirectTo, exception);
    final Map<String, Object> model = new HashMap<>();
    model.put(this.modelKey, StringEscapeUtils.escapeHtml4(exception.getMessage()));

    return new ModelAndView(new RedirectView(urlToRedirectTo), model);
}
 
Example 26
Project: easycms   File: TableServlet.java   View source code 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 27
Project: dubbo2   File: HttpProtocol.java   View source code 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 28
Project: openNaEF   File: KeseranApi.java   View source code 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 29
Project: kettle_support_kettle8.0   File: UserController.java   View source code 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 30
Project: zhkuas_ssm_maven   File: AdminSecurityInterceptor.java   View source code 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 31
Project: cas-5.1.0   File: SendTicketGrantingTicketAction.java   View source code 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 32
Project: lams   File: LearningAction.java   View source code 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 33
Project: apache-tomcat-7.0.73-with-comment   File: TestSSOnonLoginAndBasicAuthenticator.java   View source code 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 34
Project: central-medic-center   File: PatientServlet.java   View source code 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 35
Project: omero-ms-queue   File: FileStreamer.java   View source code 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 36
Project: lams   File: IndexAction.java   View source code 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 37
Project: apache-tomcat-7.0.73-with-comment   File: TestPersistentManagerIntegration.java   View source code 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 38
Project: spring-boot-start-current   File: JwtAuthenticationEntryPoint.java   View source code 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 39
Project: Mastering-Spring-5.0   File: HandlerTimeLoggingInterceptor.java   View source code 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 40
Project: osc-core   File: UiServletContext.java   View source code 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;
}