Example usage for javax.servlet ServletResponse setContentType

List of usage examples for javax.servlet ServletResponse setContentType

Introduction

In this page you can find the example usage for javax.servlet ServletResponse setContentType.

Prototype


public void setContentType(String type);

Source Link

Document

Sets the content type of the response being sent to the client, if the response has not been committed yet.

Usage

From source file:MyServlet.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    GregorianCalendar calendar = new GregorianCalendar();
    Date date1 = new Date();
    calendar.setTime(date1);/* w w  w .j  a v  a  2 s  .  c  o  m*/
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    if (hour < 9 || hour > 17) {
        chain.doFilter(request, response);
    } else {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<HEAD>");
        out.println("<TITLE>");
        out.println("Get Back to Work!");
        out.println("</TITLE>");
        out.println("</HEAD>");
        out.println("<BODY>");
        out.println("<H1>Get Back to Work!</H1>");
        out.println("Sorry, that resource is not available now.");
        out.println("</BODY>");
        out.println("</HTML>");
    }
}

From source file:org.ovirt.vdsmfake.servlet.XmlRpcFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    try {//from  w w w.ja  v  a2s.  c  o  m
        final String method = ((HttpServletRequest) request).getMethod();

        if ("GET".equals(method)) {
            response.setContentType("text/plain");
            response.getWriter().write("Hello, this is VDSM Fake.");
            return;
        }

        if (!"POST".equals(method)) {
            response.setContentType("text/plain");
            response.getWriter().write("Unsupported method: " + method);
            return;
        }

        ContextHolder.init();
        ContextHolder.setServerName(request.getServerName());

        final AppConfig conf = AppConfig.getInstance();

        final CustomHttpServletRequestWrapper wrapper = new CustomHttpServletRequestWrapper(
                (HttpServletRequest) request);

        final CustomHttpServletResponseWrapper responseWrapper = new CustomHttpServletResponseWrapper(
                (HttpServletResponse) response);

        // fix method call name - add namespace of method (required by Apache XMLRPC)
        final Document doc = XMLUtils.parseDocument(wrapper.getInputStream());
        final XPath xp = XPath.newInstance("/methodCall/methodName");
        final Element el = (Element) xp.selectSingleNode(doc);
        final String methodName = el.getText();

        final long tm = System.currentTimeMillis();

        // append namespace
        if (!conf.isProxyActive()) {
            el.setText(METHOD_CALL_NS + "." + el.getText());
        }

        // write back the new XML data
        wrapper.setInputStreamData(XMLUtils.serializeDocument(doc));

        log.info("[{}] {} starting...", new Object[] { request.getServerName(), methodName });

        chain.doFilter(wrapper, responseWrapper);

        // write communication into files
        if (conf.isLogDirSet() && conf.isMethodLoggingEnabled(methodName)) {
            int fIndex = logCounter.incrementAndGet();

            FileUtils.writeByteArrayToFile(new File(conf.getLogDir(), getPrefix(fIndex) + "_req_" + methodName),
                    wrapper.getInputStreamData());
            FileUtils.writeByteArrayToFile(new File(conf.getLogDir(), getPrefix(fIndex) + "_res_" + methodName),
                    responseWrapper.getOutputStreamData());
        }

        // write response
        responseWrapper.writeDataToStream();

        // log request info
        log.info("[{}] {} done. ({} ms, {} bytes)", new Object[] { request.getServerName(), methodName,
                Long.valueOf(System.currentTimeMillis() - tm), responseWrapper.getOutputStreamData().length });
    } catch (Exception e) {
        log.error("Cannot filter request", e);
        throw new ServletException("Error during request processing", e);
    } finally {
        ContextHolder.clear();
    }
}

From source file:cn.bc.web.filter.SetCharacterEncodingFilter.java

/**
 * Select and set (if specified) the character encoding to be used to
 * interpret request parameters for this request.
 *
 * @param request The servlet request we are processing
 * @param result The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 *///  ww w . j a  v  a2  s . co m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // Conditionally select and set the character encoding to be used
    if (ignore || (request.getCharacterEncoding() == null)) {
        String encoding = this.encoding;
        if (encoding != null) {
            request.setCharacterEncoding(encoding);
            response.setContentType("text/html;charset=" + encoding);
            if (logger.isDebugEnabled()) {
                logger.debug(":response.setCharacterEncoding(\"" + encoding + "\"");
            }
        }
    }

    // Pass control on to the next filter
    chain.doFilter(request, response);
}

From source file:org.fenixedu.bennu.core.filters.CloseTransactionFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    try {/*from   w w w  .j  av  a2 s. c  om*/
        doChain(request, response, chain);
    } catch (Error t) {
        t.printStackTrace();
        InputStream resource = request.getServletContext().getResourceAsStream("/error.html");
        if (resource != null) {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("text/html");
            IOUtils.copy(resource, outputStream);
            outputStream.flush();
        } else {
            throw t;
        }
    }
}

From source file:com.medlog.webservice.lifecycle.Security.java

private void sendProcessingError(Throwable t, ServletResponse response) {
    String stackTrace = getStackTrace(t);

    if (stackTrace != null && !stackTrace.equals("")) {
        try {//  w ww  .  j  a v  a2  s  .  c o  m
            response.setContentType("text/html");
            PrintStream ps = new PrintStream(response.getOutputStream());
            PrintWriter pw = new PrintWriter(ps);
            pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N

            // PENDING! Localize this for next official release
            pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
            pw.print(stackTrace);
            pw.print("</pre></body>\n</html>"); //NOI18N
            pw.close();
            ps.close();
            response.getOutputStream().close();
        } catch (Exception ex) {
        }
    } else {
        try {
            PrintStream ps = new PrintStream(response.getOutputStream());
            t.printStackTrace(ps);
            ps.close();
            response.getOutputStream().close();
        } catch (Exception ex) {
        }
    }
}

From source file:org.soaplab.clients.spinet.filters.DefaultFilter.java

/*************************************************************************
 *
 *************************************************************************/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    String servletPath = ((HttpServletRequest) request).getServletPath();
    // log.info ("ServletPath: " + servletPath);
    // log.info ("RealPath:    " + servletContext.getRealPath (servletPath));
    // log.info ("MimeType:    " + servletContext.getMimeType (servletContext.getRealPath (servletPath)));
    String mimeType = servletContext.getMimeType(servletContext.getRealPath(servletPath));
    if (mimeType == null) {
        response.setContentType("text/plain");
    }//from   ww  w.j a  v a  2  s .  c  o  m
    response.setCharacterEncoding("UTF-8");
    defaultRequestDispatcher.forward(request, response);
}

From source file:com.netsteadfast.greenstep.sys.GreenStepBaseFormAuthenticationFilter.java

@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
        ServletResponse response) throws Exception {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    if (!this.isAjaxRequest(httpServletRequest)) {
        httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
    } else {//  ww w .j  a  va  2s . co m
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(Constants.NO_AUTHZ_JSON_DATA);
    }
    return false;
}

From source file:cc.kune.core.server.rack.filters.rest.RESTServiceFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    final String methodName = RackHelper.getMethodName(request, pattern);
    final ParametersAdapter parameters = new ParametersAdapter(request);
    LOG.debug("JSON METHOD: '" + methodName + "' on: " + serviceClass.getSimpleName());

    response.setCharacterEncoding("utf-8");

    final String callbackMethod = getCallbackMethod(request);
    final boolean isJsonP = isJSONPRequest(callbackMethod);

    response.setContentType(isJsonP ? "text/javascript" : "text/json");

    final RESTResult result = transactionalFilter.doService(serviceClass, methodName, parameters,
            getInstance(serviceClass));/*from   ww  w . j ava2s .  c  om*/
    if (result != null) {
        if (result.getOutput() != null) {
            final Object output = wrap(result.getOutput(), isJsonP, callbackMethod);
            if (output != null) {
                final PrintWriter writer = response.getWriter();
                writer.print(output);
                writer.flush();
            } else {
                chain.doFilter(request, response);
            }

        } else {
            chain.doFilter(request, response);
        }
    }
}

From source file:com.netsteadfast.greenstep.sys.GreenStepMobileFormAuthenticationFilter.java

@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
        ServletResponse response) throws Exception {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    if (!this.isAjaxRequest(httpServletRequest)) {
        httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
    } else {//  w  w  w.j a va 2  s. c om
        response.setCharacterEncoding(Constants.BASE_ENCODING);
        response.setContentType("application/json");
        response.getWriter().write(Constants.NO_AUTHZ_JSON_DATA);
    }
    return false;
}

From source file:org.force66.mock.servletapi.MockFilterChain.java

public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    Validate.notNull(request, "Null request not allowed.");
    Validate.notNull(response, "Null response not allowed.");

    if (this.runtimeException != null) {
        throw this.runtimeException;
    }/*www  .j av  a2 s.c om*/
    if (this.ioException != null) {
        throw this.ioException;
    }
    if (this.servletException != null) {
        throw this.servletException;
    }

    try {
        Thread.sleep(sleepTimeInMillis);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (contentType != null) {
        response.setContentType(contentType);
    }
    if (outputData != null) {
        response.setContentLength(outputData.toString().length());
        response.getOutputStream().write(outputData);
    }

    if (response.getOutputStream() != null) {
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

}