Java Code Examples for javax.servlet.http.HttpServletResponse

The following examples show how to use javax.servlet.http.HttpServletResponse. These examples are extracted from open source projects. 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: knox   Author: apache   File: AtlasApiTrustedProxyHaDispatch.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void executeRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse) throws IOException {
  HttpResponse inboundResponse = null;
  try {
    inboundResponse = executeOutboundRequest(outboundRequest);
    int statusCode = inboundResponse.getStatusLine().getStatusCode();
    Header originalLocationHeader = inboundResponse.getFirstHeader("Location");


    if ((statusCode == HttpServletResponse.SC_MOVED_TEMPORARILY || statusCode == HttpServletResponse.SC_TEMPORARY_REDIRECT) && originalLocationHeader != null) {
      inboundResponse.removeHeaders("Location");
      failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, new Exception("Atlas HA redirection"));
    }

    writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);

  } catch (IOException e) {
    LOG.errorConnectingToServer(outboundRequest.getURI().toString(), e);
    failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e);
  }
}
 
Example #2
Source Project: activiti6-boot2   Author: dingziyang   File: ProcessInstanceIdentityLinkResource.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Remove an involved user to from process instance", tags = { "Process Instances" },  nickname = "deleteProcessInstanceIdentityLinks")
@ApiResponses(value = {
    @ApiResponse(code = 204, message = "Indicates the process instance was found and the link has been deleted. Response body is left empty intentionally."),
    @ApiResponse(code = 404, message = "Indicates the requested process instance was not found or the link to delete doesn’t exist. The response status contains additional information about the error.")
})
@RequestMapping(value = "/runtime/process-instances/{processInstanceId}/identitylinks/users/{identityId}/{type}", method = RequestMethod.DELETE)
public void deleteIdentityLink(@ApiParam(name = "processInstanceId", value="The id of the process instance.") @PathVariable("processInstanceId") String processInstanceId,@ApiParam(name = "identityId", value="The id of the user to delete link for.") @PathVariable("identityId") String identityId,@ApiParam(name = "type", value="Type of link to delete.") @PathVariable("type") String type,
    HttpServletResponse response) {

  ProcessInstance processInstance = getProcessInstanceFromRequest(processInstanceId);

  validateIdentityLinkArguments(identityId, type);

  getIdentityLink(identityId, type, processInstance.getId());

  runtimeService.deleteUserIdentityLink(processInstance.getId(), identityId, type);

  response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example #3
Source Project: flowable-engine   Author: flowable   File: JobExceptionStacktraceResource.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Get the exception stacktrace for a suspended job", tags = { "Jobs" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Indicates the requested job was not found and the stacktrace has been returned. The response contains the raw stacktrace and always has a Content-type of text/plain."),
        @ApiResponse(code = 404, message = "Indicates the requested job was not found or the job does not have an exception stacktrace. Status-description contains additional information about the error.")
})
@GetMapping("/management/suspended-jobs/{jobId}/exception-stacktrace")
public String getSuspendedJobStacktrace(@ApiParam(name = "jobId") @PathVariable String jobId, HttpServletResponse response) {
    Job job = getSuspendedJobById(jobId);

    String stackTrace = managementService.getSuspendedJobExceptionStacktrace(job.getId());

    if (stackTrace == null) {
        throw new FlowableObjectNotFoundException("Suspended job with id '" + job.getId() + "' does not have an exception stacktrace.", String.class);
    }

    response.setContentType("text/plain");
    return stackTrace;
}
 
Example #4
Source Project: boubei-tss   Author: boubei-com   File: DataSourceAction.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/connpool/{paramId}", method = RequestMethod.DELETE)
@ResponseBody
public Object delConnpool(HttpServletResponse response, @PathVariable("paramId") Long paramId) {
	Param param = paramService.getParam(paramId);
       paramService.delete(paramId);   
       
       // 删除“数据源列表”的下拉项
       String code = param.getCode();
       List<Param> list = ParamManager.getComboParam(PX.DATASOURCE_LIST);
	for(Param item : list) {
		if( code.equals(item.getValue()) ) {
			paramService.delete(item.getId());  
			break;
		}
	}
	
	JCache.pools.remove(code);
       
       return "成功删除数据源";
   }
 
Example #5
Source Project: flowable-engine   Author: flowable   File: FlowableCookieFilter.java    License: Apache License 2.0 6 votes vote down vote up
protected void redirectToLogin(HttpServletRequest request, HttpServletResponse response, String userId) {
    try {
        if (userId != null) {
            userCache.invalidate(userId);
        }
        
        String baseRedirectUrl = idmAppUrl + "#/login?redirectOnAuthSuccess=true&redirectUrl=";
        if (redirectUrlOnAuthSuccess != null) {
            response.sendRedirect(baseRedirectUrl + redirectUrlOnAuthSuccess);
            
        } else {
            response.sendRedirect(baseRedirectUrl + request.getRequestURL());
        }
        
    } catch (IOException e) {
        LOGGER.warn("Could not redirect to {}", idmAppUrl, e);
    }
}
 
Example #6
Source Project: rice   Author: kuali   File: EDLControllerChain.java    License: Educational Community License v2.0 6 votes vote down vote up
private void transform(EDLContext edlContext, Document dom, HttpServletResponse response) throws Exception {
	if (StringUtils.isNotBlank(edlContext.getRedirectUrl())) {
		response.sendRedirect(edlContext.getRedirectUrl());
		return;
	}
    response.setContentType("text/html; charset=UTF-8");
	Transformer transformer = edlContext.getTransformer();

       transformer.setOutputProperty("indent", "yes");
       transformer.setOutputProperty(OutputKeys.INDENT, "yes");
       String user = null;
       String loggedInUser = null;
       if (edlContext.getUserSession() != null) {
           Person wu = edlContext.getUserSession().getPerson();
           if (wu != null) user = wu.getPrincipalId();
           wu = edlContext.getUserSession().getPerson();
           if (wu != null) loggedInUser = wu.getPrincipalId();
       }
       transformer.setParameter("user", user);
       transformer.setParameter("loggedInUser", loggedInUser);
       if (LOG.isDebugEnabled()) {
       	LOG.debug("Transforming dom " + XmlJotter.jotNode(dom, true));
       }
       transformer.transform(new DOMSource(dom), new StreamResult(response.getOutputStream()));
}
 
Example #7
Source Project: jeewx-boot   Author: zhangdaiscott   File: JwWebJwidController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 初始化jwid
 */
@RequestMapping(value="/initJwid",produces="text/plain;charset=UTF-8")
@ResponseBody
public String initJwid(HttpServletRequest request, HttpServletResponse response,
		@RequestParam(value = "userId", required = true) String userId) {
	log.info("初始化公众号");
	String tree = "";
    try {
        //所有可用的权限
        List<WeixinAccountDto> allJwidList = jwWebJwidService.queryJwids();
        
        //当前角色的权限
        List<WeixinAccountDto> userJwidList = jwWebJwidService.queryJwWebJwidByUserId(userId);
       
        tree = SystemUtil.list2TreeWithCheckToJwid(allJwidList,userJwidList);
        log.info("初始化公众号: " + tree);
    }catch (Exception e){
    	log.info(e.getMessage());
    }
    return tree;
}
 
Example #8
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: UploadServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  final Part filePart = req.getPart("file");
  final String fileName = filePart.getSubmittedFileName();

  // Modify access list to allow all users with link to read file
  List<Acl> acls = new ArrayList<>();
  acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
  // the inputstream is closed by default, so we don't need to close it here
  Blob blob =
      storage.create(
          BlobInfo.newBuilder(BUCKET_NAME, fileName).setAcl(acls).build(),
          filePart.getInputStream());

  // return the public download link
  resp.getWriter().print(blob.getMediaLink());
}
 
Example #9
Source Project: mysql_perf_analyzer   Author: yahoo   File: ReportController.java    License: Apache License 2.0 6 votes vote down vote up
private ModelAndView list(HttpServletRequest req,
		HttpServletResponse resp) throws Exception
{
	int status = 0;
	String message = "OK";
	ResultList rList = null;
	UserReportManager urm = this.getUserReportManager(req);
	try
	{
		String appUser = WebAppUtil.findUserFromRequest(req);
		if(appUser==null||urm==null)
		{
			status = -1;
			message="Not login or session timed out";
		}else
		{
			rList = urm.listResultList();
		}
	}catch(Exception ex)
	{
		logger.log(Level.SEVERE,"Exception", ex);
	}
	ModelAndView mv = new ModelAndView(this.jsonView);
	mv.addObject("json_result", ResultListUtil.toJSONString(rList, null, status, message));
	return mv;
}
 
Example #10
Source Project: Insights   Author: CognizantOneDevOps   File: GrafanaAuthenticationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(priority = 4)
public void loginWithIncorrectHeader() throws Exception {
	this.mockMvc = getMacMvc();
	Map<String, String> headers = new HashMap();
	headers.put("Cookie", cookiesString);
	headers.put("Authorization", GrafanaAuthenticationTestData.authorization);
	headers.put("user", "<br></br>");
	headers.put(HttpHeaders.ORIGIN, ApplicationConfigProvider.getInstance().getInsightsServiceURL());
	headers.put(HttpHeaders.HOST, AuthenticationUtils.getHost(null));
	headers.put(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "GET, POST, OPTIONS, PUT, DELETE, PATCH");
	headers.put(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "*");
	MockHttpServletRequestBuilder builder = mockHttpServletRequestBuilderPostWithRequestParam("/user/authenticate",
			"", headers);

	ResultActions action = this.mockMvc.perform(builder.with(csrf().asHeader()));
	action.andExpect(status().is(HttpServletResponse.SC_BAD_REQUEST));
}
 
Example #11
Source Project: MusicStore   Author: MichalGoly   File: OrderController.java    License: MIT License 6 votes vote down vote up
private String addItem(HttpServletRequest request, HttpServletResponse response) {
   // retrieve or create a cart
   HttpSession session = request.getSession();
   Cart cart = (Cart) session.getAttribute("cart");
   if (cart == null) {
      cart = new Cart();
   }

   // get the product from the database, create a line item and put it into the cart
   String productCode = request.getParameter("productCode");
   Product product = ProductDB.selectProduct(productCode);
   if (product != null) {
      LineItem lineItem = new LineItem();
      lineItem.setProduct(product);
      cart.addItem(lineItem);
   }

   session.setAttribute("cart", cart);
   return "/cart/cart.jsp";
}
 
Example #12
Source Project: blog-sample   Author: jitwxs   File: ValidateCodeFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if(isProtectedUrl(request)) {
        String verifyCode = request.getParameter(SecurityConstants.VALIDATE_CODE_PARAMETER);
        if(!validateVerify(verifyCode)) {
            //手动设置异常
            request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION",new DisabledException("验证码输入错误"));
            // 转发到错误Url
            request.getRequestDispatcher(SecurityConstants.VALIDATE_CODE_ERR_URL).forward(request,response);
        } else {
            filterChain.doFilter(request,response);
        }
    } else {
        filterChain.doFilter(request,response);
    }
}
 
Example #13
Source Project: javaee8-cookbook   Author: eldermoraes   File: AuthenticationMechanism.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {

    if (httpMessageContext.isAuthenticationRequest()) {

        Credential credential = httpMessageContext.getAuthParameters().getCredential();
        if (!(credential instanceof CallerOnlyCredential)) {
            throw new IllegalStateException("Invalid mechanism");
        }

        CallerOnlyCredential callerOnlyCredential = (CallerOnlyCredential) credential;

        if ("user".equals(callerOnlyCredential.getCaller())) {
            return httpMessageContext.notifyContainerAboutLogin(callerOnlyCredential.getCaller(), new HashSet<>(Arrays.asList("role1","role2")));
        } else{
            throw new AuthenticationException();
        }

    }

    return httpMessageContext.doNothing();
}
 
Example #14
Source Project: Aooms   Author: yuboon   File: AoomsGlobalErrorController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 覆盖默认的HTML响应
 */
@Override
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    //请求的状态
    HttpStatus status = getStatus(request);
    //isIncludeStackTrace(request, MediaType.TEXT_HTML)

    // message
    // status
    // trace
    // path
    // timestamp
    // error

    // 包含异常堆栈信息
    Map<String, Object> model = getErrorAttributes(request, true);
    ModelAndView modelAndView = resolveErrorView(request, response, status, model);

    //指定自定义的视图
    return new ModelAndView("/error.html", model);
}
 
Example #15
Source Project: boubei-tss   Author: boubei-com   File: CacheAction.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/item/{code}", method = RequestMethod.DELETE)
  public void removeCachedItem(HttpServletResponse response, 
  		@PathVariable String code, 
  		@RequestParam("key") String key) {
  	
      Pool pool = cache.getPool(code);
boolean rt = pool.destroyByKey(key);
      printSuccessMessage( !rt ? "destroy succeed。" : EX.CACHE_5);
  }
 
Example #16
public ActionForward deleteExternalUnit(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws FenixServiceException {

    final Unit unit = getUnit(request);
    final Unit parent = getAnyParentUnit(unit);

    try {
        DeleteExternalUnit.run(unit);
    } catch (final DomainException e) {
        addActionMessage("error", request, e.getMessage());
        request.setAttribute("unit", unit);
        return mapping.findForward("prepareDeleteUnit");
    }

    return viewUnit(mapping, request, parent);
}
 
Example #17
Source Project: eplmp   Author: polarsys   File: JWTSAM.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {

    HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();

    LOGGER.log(Level.FINE, "Validating request @" + request.getMethod() + " " + request.getRequestURI());

    String authorization = request.getHeader("Authorization");
    String[] splitAuthorization = authorization.split(" ");
    String jwt = splitAuthorization[1];

    JWTokenUserGroupMapping jwTokenUserGroupMapping = JWTokenFactory.validateAuthToken(key, jwt);

    if (jwTokenUserGroupMapping != null) {

        UserGroupMapping userGroupMapping = jwTokenUserGroupMapping.getUserGroupMapping();
        CallerPrincipalCallback callerPrincipalCallback = new CallerPrincipalCallback(clientSubject, userGroupMapping.getLogin());
        GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, new String[]{userGroupMapping.getGroupName()});
        Callback[] callbacks = new Callback[]{callerPrincipalCallback, groupPrincipalCallback};

        try {
            callbackHandler.handle(callbacks);
        } catch (IOException | UnsupportedCallbackException e) {
            throw new AuthException(e.getMessage());
        }

        JWTokenFactory.refreshTokenIfNeeded(key, response, jwTokenUserGroupMapping);

        return AuthStatus.SUCCESS;
    }

    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return AuthStatus.FAILURE;

}
 
Example #18
Source Project: renren-fast   Author: zhaoqicheng   File: OAuth2Filter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    //获取请求token,如果token不存在,直接返回401
    String token = getRequestToken((HttpServletRequest) request);
    if(StringUtils.isBlank(token)){
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String json = new Gson().toJson(R.error(HttpStatus.SC_UNAUTHORIZED, "invalid token"));
        httpResponse.getWriter().print(json);

        return false;
    }

    return executeLogin(request, response);
}
 
Example #19
Source Project: oslits   Author: jht3820   File: Dpl1100Controller.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Dpl1100 배포계획에서 요구사항을 배정 제외한다.
 * @param
 * @return
 * @exception Exception
 */
@RequestMapping(value = "/dpl/dpl1000/dpl1100/deleteDpl1100Dpl.do")
public ModelAndView deleteDpl1100Dpl(HttpServletRequest request,HttpServletResponse response, ModelMap model) throws Exception {
	
	try {
		// request 파라미터를 map으로 변환
		Map<String, String> paramMap = RequestConvertor.requestParamToMapAddSelInfo(request, true);
		
		HttpSession ss = request.getSession();
		// 프로젝트 ID를 가져와 Map에 추가한다.
		paramMap.put("prjId", ss.getAttribute("selPrjId").toString());
		
		//배포계획 요구사항 배정 제외
		dpl1100Service.deleteDpl1100ReqDplInfo(paramMap);
		
		// 삭제 성공여부 및 삭제성공 메시지 세팅
		model.addAttribute("errorYn", "N");
		model.addAttribute("message",egovMessageSource.getMessage("success.common.delete"));
		return new ModelAndView("jsonView");
		
	} catch (Exception ex) {
		Log.error("deleteDpl1100Dpl()", ex);
		
		// 삭제 실패여부 및 삭제실패 메시지 세팅
		model.addAttribute("errorYn", "Y");
		model.addAttribute("message",egovMessageSource.getMessage("fail.common.delete"));
		return new ModelAndView("jsonView");
	}
}
 
Example #20
Source Project: sakai   Author: sakaiproject   File: SkinnableLogin.java    License: Educational Community License v2.0 5 votes vote down vote up
public void sendResponse(LoginRenderContext rcontext, HttpServletResponse res,
		String template, String contentType) throws IOException
{
	// headers
	if (contentType == null)
	{
		res.setContentType("text/html; charset=UTF-8");
	}
	else
	{
		res.setContentType(contentType);
	}
	res.addDateHeader("Expires", System.currentTimeMillis()
			- (1000L * 60L * 60L * 24L * 365L));
	res.addDateHeader("Last-Modified", System.currentTimeMillis());
	res.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
	res.addHeader("Pragma", "no-cache");

	// get the writer
	PrintWriter out = res.getWriter();

	try
	{
		LoginRenderEngine rengine = rcontext.getRenderEngine();
		rengine.render(template, rcontext, out);
	}
	catch (Exception e)
	{
		throw new RuntimeException("Failed to render template ", e);
	}

}
 
Example #21
Source Project: jeewx   Author: zhangdaiscott   File: QywxGroupController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 跳转到添加页面
 * @return
 */
@RequestMapping(params = "toAdd",method ={RequestMethod.GET, RequestMethod.POST})
public void toAddDialog(@RequestParam(required = false, value = "pid" ) String pid,HttpServletRequest request,HttpServletResponse response)throws Exception{
	 VelocityContext velocityContext = new VelocityContext();
	 QywxGroup qywxGroup = null;
	 if(!StringUtil.isEmpty(pid)){
		 qywxGroup = qywxGroupDao.get(pid);
	 }
	 velocityContext.put("qywxGroup",qywxGroup);
	 String viewName = "qywx/base/qywxGroup-add.vm";
	 ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example #22
Source Project: ambari-logsearch   Author: apache   File: LogsearchTrustedProxyFilter.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 doAsUserName = request.getParameter("doAs");
  final List<GrantedAuthority> authorities = RoleDao.createDefaultAuthorities();
  final UserDetails principal = new User(doAsUserName, "", authorities);
  final AbstractAuthenticationToken finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", authorities);
  WebAuthenticationDetails webDetails = new WebAuthenticationDetails(request);
  finalAuthentication.setDetails(webDetails);
  SecurityContextHolder.getContext().setAuthentication(finalAuthentication);
  logger.info("Logged into Log Search User as doAsUser = {}", doAsUserName);
  return finalAuthentication;
}
 
Example #23
Source Project: Spring5Tutorial   Author: JustinSDK   File: HtmlSanitizer.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void doFilter(HttpServletRequest request, 
        HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {

    chain.doFilter(new SanitizerWrapper(request), response);
}
 
Example #24
Source Project: tus-java-server   Author: tomdesair   File: CoreOptionsRequestHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void process(HttpMethod method, TusServletRequest servletRequest,
                    TusServletResponse servletResponse, UploadStorageService uploadStorageService,
                    String ownerKey) {

    if (uploadStorageService.getMaxUploadSize() > 0) {
        servletResponse.setHeader(HttpHeader.TUS_MAX_SIZE,
                Objects.toString(uploadStorageService.getMaxUploadSize()));
    }

    servletResponse.setHeader(HttpHeader.TUS_VERSION, TusFileUploadService.TUS_API_VERSION);

    servletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
 
Example #25
Source Project: yawp   Author: feroult   File: EndpointServlet.java    License: MIT License 5 votes vote down vote up
protected void response(HttpServletResponse resp, HttpResponse httpResponse) throws IOException {
    if (httpResponse == null) {
        new JsonResponse().execute(resp);
    } else {
        httpResponse.execute(resp);
    }
}
 
Example #26
Source Project: SI   Author: iotoasis   File: ApiServlet.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void processDeviceResponse(HttpServletRequest req, HttpServletResponse resp, JSONArray result)
        throws IOException {
	
	String response = result.toString();
	System.out.println("resp : "+response);
    if ( Util.isNoE(response) && result.length() == 0 ) {
        LOG.warn(String.format("Request %s%s timed out.", req.getServletPath(), req.getPathInfo()));
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.getWriter().append("Request timeout").flush();
    } else {
     resp.setContentType("application/json");
     resp.getOutputStream().write(response.getBytes());
     resp.setStatus(HttpServletResponse.SC_OK);
    }
}
 
Example #27
Source Project: java-course-ee   Author: java-course-ee   File: GetRandom.java    License: MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

        Thread.sleep(3000);
        out.print(Math.round(Math.random() * 1000));
    } catch (InterruptedException ex) {
        System.err.println("ERROR: " + ex.getMessage());
    } finally {
        out.close();
    }
}
 
Example #28
Source Project: proxyee-down   Author: shakenetwork   File: PacController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/pd.pac")
public void pac(HttpServletResponse response) {
  response.setHeader("Content-Type", "application/x-ns-proxy-autoconfig");
  response.setHeader("Cache-Control", "no-cache");
  response.setHeader("Pragma", "no-cache");
  response.setDateHeader("Expires", 0);
  try (
      OutputStream out = response.getOutputStream()
  ) {
    out.write(
        pacTemple.replace("{port}", ContentManager.CONFIG.get().getProxyPort() + "").getBytes());
  } catch (Exception e) {
    LOGGER.warn("res error:", e);
  }
}
 
Example #29
Source Project: ymate-platform-v2   Author: suninformation   File: AbstractView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IView addIntHeader(String name, int value) {
    HttpServletResponse _response = WebContext.getResponse();
    if (_response.containsHeader(name)) {
        _response.addIntHeader(name, value);
    } else {
        _response.setIntHeader(name, value);
    }
    return this;
}
 
Example #30
Source Project: sakai   Author: sakaiproject   File: SiteResetHandler.java    License: Educational Community License v2.0 5 votes vote down vote up
@Override
public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res,
		Session session) throws PortalHandlerException
{
	if ((parts.length > 2) && (parts[1].equals(SiteResetHandler.URL_FRAGMENT)))
	{
		try
		{
			String siteUrl = req.getContextPath() + "/site"
					+ Web.makePath(parts, 2, parts.length);
			// Make sure to add the parameters such as panel=Main
			String queryString = Validator.generateQueryString(req);
			if (queryString != null)
			{
				siteUrl = siteUrl + "?" + queryString;
			}
			portalService.setResetState("true");
			res.sendRedirect(siteUrl);
			return RESET_DONE;
		}
		catch (Exception ex)
		{
			throw new PortalHandlerException(ex);
		}
	}
	else
	{
		return NEXT;
	}
}