javax.servlet.http.HttpServletResponse Java Examples

The following examples show how to use javax.servlet.http.HttpServletResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EDLControllerChain.java    From rice with Educational Community License v2.0 7 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 #2
Source File: AtlasApiTrustedProxyHaDispatch.java    From knox with 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 #3
Source File: ProcessInstanceIdentityLinkResource.java    From activiti6-boot2 with 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 #4
Source File: JobExceptionStacktraceResource.java    From flowable-engine with 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 #5
Source File: DataSourceAction.java    From boubei-tss with 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 #6
Source File: FlowableCookieFilter.java    From flowable-engine with 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 #7
Source File: JwWebJwidController.java    From jeewx-boot with 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 File: UploadServlet.java    From java-docs-samples with 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 File: ReportController.java    From mysql_perf_analyzer with 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 File: GrafanaAuthenticationTest.java    From Insights with 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 File: OrderController.java    From MusicStore with 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 File: ValidateCodeFilter.java    From blog-sample with 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 File: AuthenticationMechanism.java    From javaee8-cookbook with 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 File: AoomsGlobalErrorController.java    From Aooms with 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 File: CacheAction.java    From boubei-tss with 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
Source File: ExternalUnitsDispatchAction.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 File: JWTSAM.java    From eplmp with 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 File: OAuth2Filter.java    From renren-fast with 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 File: Dpl1100Controller.java    From oslits with 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 File: SkinnableLogin.java    From sakai with 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 File: QywxGroupController.java    From jeewx with 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 File: LogsearchTrustedProxyFilter.java    From ambari-logsearch with 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 File: HtmlSanitizer.java    From Spring5Tutorial with 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 File: CoreOptionsRequestHandler.java    From tus-java-server with 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 File: EndpointServlet.java    From yawp with 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 File: ApiServlet.java    From SI with 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 File: GetRandom.java    From java-course-ee with 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 File: PacController.java    From proxyee-down with 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 File: AbstractView.java    From ymate-platform-v2 with 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 File: SiteResetHandler.java    From sakai with 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;
	}
}