Java Code Examples for javax.servlet.ServletResponse.setContentType()

The following are Jave code examples for showing how to use setContentType() of the javax.servlet.ServletResponse class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: zkAdmin   File: LoginFilter.java   Source Code and License Vote up 9 votes
@Override
public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    if (this.isAccessAllowed(request, response, mappedValue) && this.isLoginRequest(request, response)) {
        if (((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("{\"code\":200,\"info\":\"already logined\"}");
            out.flush();
            out.close();
        }else {
            WebUtils.issueRedirect(request,response,this.getSuccessUrl());
        }
        return false;
    }
    return super.onPreHandle(request, response, mappedValue);
}
 
Example 2
Project: dremio-oss   File: IndexServlet.java   Source Code and License Vote up 8 votes
@Override
public void service(ServletRequest servletRequest, ServletResponse response) throws ServletException, IOException {
  ClientSettings settings = new ClientSettings(
      options.getOption(SupportService.SUPPORT_EMAIL_ADDR),
      options.getOption(SupportService.SUPPORT_EMAIL_SUBJECT),
      options.getOption(SupportService.OUTSIDE_COMMUNICATION_DISABLED),
      options.getOption(AccelerationOptions.ENABLE_SUBHOUR_POLICIES),
      options.getOption(UIOptions.ALLOW_LOWER_PROVISIONING_SETTINGS),
      options.getOption(UIOptions.TABLEAU_TDS_MIMETYPE));

  String environment = config.allowTestApis ? "DEVELOPMENT" : "PRODUCTION";
  final ServerData indexConfig = new ServerData(environment, serverHealthMonitor, config.getConfig(), settings, getVersionInfo(), supportService.getClusterId().getIdentity());

  Template tmp = templateCfg.getTemplate("/index.html");

  response.setContentType("text/html; charset=utf-8");
  OutputStreamWriter outputWriter = new OutputStreamWriter(response.getOutputStream());
  try {
    tmp.process(ImmutableMap.of("dremio", indexConfig), outputWriter);
    outputWriter.flush();
    outputWriter.close();
  } catch (TemplateException e) {
    throw new IOException("Error rendering index.html template", e);
  }
}
 
Example 3
Project: incubator-servicecomb-java-chassis   File: RestAsyncListener.java   Source Code and License Vote up 7 votes
@Override
public void onTimeout(AsyncEvent event) throws IOException {
  // in this time, maybe:
  // 1.invocation in executor's queue
  // 2.already executing in executor
  // 3.already send response
  // to avoid concurrent, must lock request
  ServletRequest request = event.getSuppliedRequest();
  HttpServletRequestEx requestEx = (HttpServletRequestEx) request.getAttribute(RestConst.REST_REQUEST);

  synchronized (requestEx) {
    ServletResponse response = event.getAsyncContext().getResponse();
    if (!response.isCommitted()) {
      LOGGER.error("Rest request timeout, method {}, path {}.", requestEx.getMethod(), requestEx.getRequestURI());
      // invocation in executor's queue
      response.setContentType(MediaType.APPLICATION_JSON);

      // we don't know if developers declared one statusCode in contract
      // so we use cse inner statusCode here
      ((HttpServletResponse) response).setStatus(ExceptionFactory.PRODUCER_INNER_STATUS_CODE);
      PrintWriter out = response.getWriter();
      out.write(TIMEOUT_MESSAGE);
      response.flushBuffer();
    }

    request.removeAttribute(RestConst.REST_REQUEST);
  }
}
 
Example 4
Project: YiDu-Novel   File: UrlRewriteFilter.java   Source Code and License Vote up 7 votes
/**
 * Show the status of the conf and the filter to the user.
 * 
 * @param request
 *            to get status info from
 * @param response
 *            response to show the status on.
 * @throws java.io.IOException
 *             if the output cannot be written
 */
private void showStatus(final HttpServletRequest request, final ServletResponse response) throws IOException {

    log.debug("showing status");

    if (allowConfSwapViaHttp) {
        String newConfPath = request.getParameter("conf");
        if (!StringUtils.isBlank(newConfPath)) {
            confPath = newConfPath;
            loadUrlRewriterLocal();
        }
    }

    Status status = new Status(confLastLoaded, this);
    status.displayStatusInContainer(request);

    response.setContentType("text/html; charset=UTF-8");
    response.setContentLength(status.getBuffer().length());

    final PrintWriter out = response.getWriter();
    out.write(status.getBuffer().toString());
    out.close();

}
 
Example 5
Project: Yidu   File: UrlRewriteFilter.java   Source Code and License Vote up 7 votes
/**
 * Show the status of the conf and the filter to the user.
 * 
 * @param request
 *            to get status info from
 * @param response
 *            response to show the status on.
 * @throws java.io.IOException
 *             if the output cannot be written
 */
private void showStatus(final HttpServletRequest request, final ServletResponse response) throws IOException {

    log.debug("showing status");

    if (allowConfSwapViaHttp) {
        String newConfPath = request.getParameter("conf");
        if (!StringUtils.isBlank(newConfPath)) {
            confPath = newConfPath;
            loadUrlRewriterLocal();
        }
    }

    Status status = new Status(confLastLoaded, this);
    status.displayStatusInContainer(request);

    response.setContentType("text/html; charset=UTF-8");
    response.setContentLength(status.getBuffer().length());

    final PrintWriter out = response.getWriter();
    out.write(status.getBuffer().toString());
    out.close();

}
 
Example 6
Project: JavaEE   File: HelloServlet.java   Source Code and License Vote up 7 votes
public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.println("<!DOCTYPE html>\n"+
        "<html>\n"+
        "<head>\n"+
        "<meta charset='UTF-8'>\n"+
        "<title>Hello Servlet</title>\n"+
        "</head>\n"+
        "<body>\n"+
        "<h2>Hello Servlet!</h2>\n"+
        "Go <a href='"+
            request.getServletContext().getContextPath()+
        "'>Back</a>\n"+
        "</body>\n"+
        "</html>");
    pw.close();
}
 
Example 7
Project: automat   File: TokenFilter.java   Source Code and License Vote up 6 votes
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	if (isWhiteReq(request.getRequestURI())) {
		chain.doFilter(request, response);
	} else {
		String token = request.getHeader("token");
		if (StringUtils.isNotBlank(token)) {
			try {
				Token tokenInfo = TokenUtil.getTokenInfo(token);
				if (tokenInfo != null) {
					Long now = System.currentTimeMillis();
					if (now - tokenInfo.getTime() < 1000 * 60 * 30) {
						String value = tokenInfo.getValue();
						TokenUtil.setTokenInfo(token, value);
						WebUtil.saveCurrentUser(request, value);
					}
				}
			} catch (Exception e) {
				logger.error("token检查发生异常:", e);
			}
		}
		// 响应
		if (DataUtil.isEmpty(WebUtil.getCurrentUser(request))) {
			response.setContentType("text/html; charset=UTF-8");
			Map<String, Object> modelMap = InstanceUtil.newLinkedHashMap();
			modelMap.put("httpCode", HttpCode.UNAUTHORIZED.value());
			modelMap.put("msg", HttpCode.UNAUTHORIZED.msg());
			modelMap.put("timestamp", System.currentTimeMillis());
			PrintWriter out = response.getWriter();
			out.println(JSON.toJSONString(modelMap));
			out.flush();
			out.close();
		} else {
			chain.doFilter(request, response);
		}
	}
}
 
Example 8
Project: atbash-octopus   File: UserFilter.java   Source Code and License Vote up 6 votes
@Override
protected void redirectToLogin(ServletRequest req, ServletResponse res) throws IOException {
    HttpServletRequest request = (HttpServletRequest) req;

    if ("partial/ajax".equals(request.getHeader("Faces-Request"))) {
        res.setContentType("text/xml");
        res.setCharacterEncoding("UTF-8");

        String loginUrl = getLoginUrl();
        if (loginUrl.startsWith("/") || !loginUrl.startsWith("http")) {
            // If it is a relative URL, use the context path.
            loginUrl = request.getContextPath() + loginUrl;
        }
        res.getWriter().printf(FACES_REDIRECT_XML, loginUrl);
    } else {
        super.redirectToLogin(req, res);
    }
}
 
Example 9
Project: zkAdmin   File: LoginFilter.java   Source Code and License Vote up 6 votes
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    if (isLoginRequest(request, response)) {
        if (isLoginSubmission(request, response)) {
            if (log.isTraceEnabled()) {
                log.trace("Login submission detected.  Attempting to execute login.");
            }
            return executeLogin(request, response);
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Login page view.");
            }
            // allow them to see the login page ;)
            return true;
        }
    } else {
        if (log.isTraceEnabled()) {
            log.trace("Attempting to access a path which requires authentication.  Forwarding to the "
                    + "Authentication url [" + getLoginUrl() + "]");
        }
        if (!((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")) {
            saveRequestAndRedirectToLogin(request, response);
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("{\"code\":-203,\"info\":\"login\"}");
            out.flush();
            out.close();
        }
        return false;
    }
}
 
Example 10
Project: zkAdmin   File: LoginFilter.java   Source Code and License Vote up 6 votes
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    if (!httpServletRequest.getRequestURL().toString().endsWith(".json")) {
        issueSuccessRedirect(request, response);
    } else {

        httpServletResponse.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.println("{\"code\":200,\"info\":\"登入成功\"}");
        out.flush();
        out.close();
    }

    return true;
}
 
Example 11
Project: zkAdmin   File: LoginFilter.java   Source Code and License Vote up 6 votes
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
    if (!((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")) {
        setFailureAttribute(request, e);
        return true;
    }
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        String message = e.getClass().getSimpleName();
        if ("IncorrectCredentialsException".equals(message)
                || "UnknownAccountException".equals(message)
                ) {
            out.println("{\"code\":-100010,\"info\":\"账号或密码错误\"}");
        }else if("ExcessiveAttemptsException".equals(message)){
            out.println("{\"code\":-100020,\"info\":\"密码错误次数超过限制,请10分钟后重试!\"}");
        }else if("LockedAccountException".equals(message)){
            out.println("{\"code\":-100030,\"info\":\"账号已停用!\"}");
        } else {
            out.println("{\"code\":-100500,\"info\":\"未知错误\"}");
        }
        out.flush();
        out.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return false;
}
 
Example 12
Project: myfaces-trinidad   File: CoreRenderKit.java   Source Code and License Vote up 6 votes
/**
 * @todo Generalize???
 */
private Writer _getHtmlWriter(FacesContext context) throws IOException
{
  ServletResponse response = (ServletResponse)
    context.getExternalContext().getResponse();
  response.setContentType(_HTML_MIME_TYPE);
  return response.getWriter();
}
 
Example 13
Project: servlet-auth   File: AuthRequestFilter.java   Source Code and License Vote up 5 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession(false);
    String loginURI = req.getContextPath() + "/login";

    boolean loggedIn = session != null && session.getAttribute("user") != null;
    boolean loginRequest = req.getRequestURI().equals(loginURI);
    boolean resourceRequest = req.getRequestURI().startsWith(req.getContextPath() + RESOURCE_IDENTIFIER + "/");
    boolean ajaxRequest = "partial/ajax".equals(req.getHeader("Faces-Request"));

    if (loggedIn || loginRequest || resourceRequest) {
        if (!resourceRequest) {
            res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            res.setHeader("Pragma", "no-cache");
            res.setDateHeader("Expires", 0);
        }
        chain.doFilter(new AuthRequestWrapper((HttpServletRequest) request), response);
    } else if (ajaxRequest) {
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().printf(AJAX_REDIRECT_XML, loginURI);
    } else {
        res.sendRedirect(loginURI);
    }
}
 
Example 14
Project: JAVA-   File: TokenFilter.java   Source Code and License Vote up 5 votes
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	if (isWhiteReq(request.getRequestURI())) {
		chain.doFilter(request, response);
	} else {
		String token = request.getHeader("token");
		if (StringUtils.isNotBlank(token)) {
			try {
				Token tokenInfo = TokenUtil.getTokenInfo(token);
				if (tokenInfo != null) {
					Long now = System.currentTimeMillis();
					if (now - tokenInfo.getTime() < 1000 * 60 * 30) {
						String value = tokenInfo.getValue();
						TokenUtil.setTokenInfo(token, value);
						WebUtil.saveCurrentUser(request, value);
					}
				}
			} catch (Exception e) {
				logger.error("token检查发生异常:", e);
			}
		}
		// 响应
		if (DataUtil.isEmpty(WebUtil.getCurrentUser(request))) {
			response.setContentType("text/html; charset=UTF-8");
			Map<String, Object> modelMap = InstanceUtil.newLinkedHashMap();
			modelMap.put("httpCode", HttpCode.UNAUTHORIZED.value());
			modelMap.put("msg", HttpCode.UNAUTHORIZED.msg());
			modelMap.put("timestamp", System.currentTimeMillis());
			PrintWriter out = response.getWriter();
			out.println(JSON.toJSONString(modelMap));
			out.flush();
			out.close();
		} else {
			chain.doFilter(request, response);
		}
	}
}
 
Example 15
Project: apache-tomcat-7.0.73-with-comment   File: TestStandardContext.java   Source Code and License Vote up 5 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    response.setContentType("text/plain");
    response.getWriter().print("Filter");
    chain.doFilter(request, response);
}
 
Example 16
Project: lazycat   File: RequestFilter.java   Source Code and License Vote up 4 votes
private void sendErrorWhenNotHttp(ServletResponse response) throws IOException {
	response.setContentType(PLAIN_TEXT_MIME_TYPE);
	response.getWriter().write(sm.getString("http.403"));
	response.getWriter().flush();
}
 
Example 17
Project: tomcat7   File: RequestFilter.java   Source Code and License Vote up 4 votes
private void sendErrorWhenNotHttp(ServletResponse response)
        throws IOException {
    response.setContentType(PLAIN_TEXT_MIME_TYPE);
    response.getWriter().write(sm.getString("http.403"));
    response.getWriter().flush();
}
 
Example 18
Project: myfaces-trinidad   File: ShowMessageBackingBean.java   Source Code and License Vote up 4 votes
public String downloadAttachment() throws IOException, MessagingException
{
  if (_attachmentToDownload == null)
  {
    _LOG.severe("No attachment available");
    return null;
  }

  _message.getMessage().getFolder().open(Folder.READ_ONLY);

  InputStream in = _attachmentToDownload.getInputStream();

  FacesContext context = FacesContext.getCurrentInstance();
  // Get the ServletResponse;  nothing on ExternalContext is sufficient
  ServletResponse response = (ServletResponse)
    context.getExternalContext().getResponse();
  response.setContentType(_attachmentToDownload.getContentType());

  // If the size of the attachment is known, pass that on.
  int size = _attachmentToDownload.getSize();
  if (size >= 0)
  {
    response.setContentLength(size);
  }

  if (_LOG.isLoggable(Level.INFO))
    _LOG.info("Downloading content+ [size=" + size +",contentType=" +
              _attachmentToDownload.getContentType() + "]");

  if (response instanceof HttpServletResponse)
  {
    String filename = _attachmentToDownload.getFileName();
    if (filename != null)
    {
      ((HttpServletResponse) response).setHeader(
          "Content-disposition",
          "attachment; filename=\"" + filename + "\"");
    }
  }

  // Pass the text along, 128K at a time.
  try
  {
    OutputStream out = response.getOutputStream();
    try
    {
      byte[] buffer = new byte[131072];
      while (true)
      {
        int count = in.read(buffer);
        if (count < 0)
          break;

        out.write(buffer, 0, count);
      }
    }
    // Close up the response
    finally
    {
      // And tell JSF that we handled everything
      context.responseComplete();
      out.close();
    }
  }
  // And make sure the folder got closed
  finally
  {
    _message.getMessage().getFolder().close(false);
  }

  return null;
}
 
Example 19
Project: minsx-authorization-server   File: RequestUtil.java   Source Code and License Vote up 4 votes
public static void responseJson(ServletResponse response, Object data) throws IOException {
    response.setContentType("application/json;charset=UTF-8");
    response.getWriter().write(JSON.toJSONString(data));
    response.getWriter().flush();
    response.getWriter().close();
}
 
Example 20
Project: jaffa-framework   File: SecurityFilter.java   Source Code and License Vote up 4 votes
/** Perform the filter action.
 * @param request ServletRequest the request being perfomred
 * @param response ServletResponse the response to be sent
 * @param chain FilterChain the filter chain to continue execution of
 * @throws IOException 
 * @throws ServletException 
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    log.debug("doFilter()");

    HttpSession session = ((HttpServletRequest) request).getSession(false);

    log.debug("Getting session principal");
    Principal principal = (Principal) session.getAttribute("org.jaffa.security.filter.SecurityFilterPrincipal");
    if(principal == null) {
       // principal was null, not authenticated/new session

       String user = ((HttpServletRequest) request).getRemoteUser().toUpperCase();
       if(user == null) {
          throw new ServletException("Request user not found.");
       }

       boolean authenticated = authenticateUser(user);

       if(!authenticated) {
          log.debug("User ["+user+"] failed authentication");

          response.setContentType("text/html");

          PrintWriter out = response.getWriter();
          out.println("<html><head><title>Authentication Failed</title></head><body>");
          out.println("<h2>Sorry you are not authorized to use this application</h2>");
          out.println("</body></html>");
          out.close();

          log.debug("Invalidating session");
          session.invalidate();

          log.debug("return");
          return;
       }

       log.debug("Getting Roles for user [" + user + "]");
       List roles = getRoles(user);

       log.debug("Setting session principal");
       principal = new SecurityFilterPrincipal(user, roles);
       session.setAttribute("org.jaffa.security.filter.SecurityFilterPrincipal", principal);
    }
    log.debug("Principal [" + principal.getName() + "]");

    log.debug("Wrapping request through SecurityFilterRequestWrapper");
    request = new SecurityFilterRequestWrapper((HttpServletRequest) request);

    log.debug("chain.doFilter()");
    chain.doFilter(request, response);
}