Example usage for javax.servlet.http HttpServletResponse setContentType

List of usage examples for javax.servlet.http HttpServletResponse setContentType

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse 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:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Admin.CRUDUsuarios.java

protected static void crearUsuario(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println(request.getParameter("5"));
    ArrayList r = CtrlAdmin.crearUsuario(request.getParameter("1"), //Nombre
            request.getParameter("2"), //Apellidos
            request.getParameter("3"), //Tipo de documento
            request.getParameter("4"), //documento
            request.getParameter("5"), //Correo= usuario
            request.getParameter("6"), //passworld
            request.getParameter("7").charAt(0)//rol
    );//www  .  j  a va  2s.c o  m

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    if (r.get(0) == "error") {
        JSONObject obj = new JSONObject();
        if (r.get(1) == "usuario") {
            obj.put("isError", true);
            obj.put("errorDescrip", "El usuario ya existe");
        } else if (r.get(1) == "contrasena") {
            obj.put("isError", true);
            obj.put("errorDescrip", "La contrasea es invalida");
        } else if (r.get(1) == "documento") {
            obj.put("isError", true);
            obj.put("errorDescrip", "El documento ya est registrado");
        } else if (r.get(1) == "tipoDocumento") {
            obj.put("isError", true);
            obj.put("errorDescrip", "El tipo de documento es invalido");
        } else if (r.get(1) == "correo") {
            obj.put("isError", true);
            obj.put("errorDescrip", "El correo ya est registrado");
        } else if (r.get(1) == "correo1") {
            obj.put("isError", true);
            obj.put("errorDescrip", "El correo no es valido");
        } else if (r.get(1) == "nombre") {
            obj.put("isError", true);
            obj.put("errorDescrip", "Los nombres o apellidos son incorrectos");
        } else if (r.get(1) == "rol") {
            obj.put("isError", true);
            obj.put("errorDescrip", "El rol es invalido, los posibles valores son: E, P y A");
        } else
            Util.errordeRespuesta(r, out);
        out.print(obj);
    } else if (r.get(0) == "isExitoso") {
        JSONObject obj = new JSONObject();
        obj.put("Exitoso", true);
        out.print(obj);
    } else
        Util.errordeRespuesta(r, out);
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Admin.CUDEventos.java

protected static void crearTaller(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ArrayList r = CtrlAdmin.crearTaller(request.getParameter("1"), // nombre
            request.getParameter("2"), // descripcin
            request.getParameter("4"), // fin registro (Fecha hasta donde est permitido registrarse)
            request.getParameter("3"), // inicio del taller
            request.getParameter("4"), // fin del taller
            Integer.parseInt(request.getParameter("5")), // costo
            Integer.parseInt(request.getParameter("6")) // cupos
    );//from   w w w .jav a2  s .  c  o m

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    if (r.get(0) == "error") {
        JSONObject obj = new JSONObject();
        obj.put("isError", true);
        obj.put("errorDescrip", r.get(1));
        out.print(obj);
    } else if (r.get(0) == "isExitoso") {
        JSONObject obj = new JSONObject();
        obj.put("Exitoso", true);
        out.print(obj);
    } else
        Util.errordeRespuesta(r, out);
}

From source file:com.googlecode.jsonplugin.JSONUtil.java

public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    if (TextUtils.stringSet(serializationParams.getSerializedJSON()))
        stringBuilder.append(serializationParams.getSerializedJSON());

    if (TextUtils.stringSet(serializationParams.getWrapPrefix()))
        stringBuilder.insert(0, serializationParams.getWrapPrefix());
    else if (serializationParams.isWrapWithComments()) {
        stringBuilder.insert(0, "/* ");
        stringBuilder.append(" */");
    } else if (serializationParams.isPrefix())
        stringBuilder.insert(0, "{}&& ");

    if (TextUtils.stringSet(serializationParams.getWrapSuffix()))
        stringBuilder.append(serializationParams.getWrapSuffix());

    String json = stringBuilder.toString();

    if (log.isDebugEnabled()) {
        log.debug("[JSON]" + json);
    }/*from   ww  w. j av  a  2s. c o m*/

    HttpServletResponse response = serializationParams.getResponse();

    //status or error code
    if (serializationParams.getStatusCode() > 0)
        response.setStatus(serializationParams.getStatusCode());
    else if (serializationParams.getErrorCode() > 0)
        response.sendError(serializationParams.getErrorCode());

    //content type
    if (serializationParams.isSmd())
        response.setContentType("application/json-rpc;charset=" + serializationParams.getEncoding());
    else
        response.setContentType(
                serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding());

    if (serializationParams.isNoCache()) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
    }

    if (serializationParams.isGzip()) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes());
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(serializationParams.getEncoding()).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Admin.CUDEventos.java

protected static void actualizarTaller(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    ArrayList r = CtrlAdmin.actualizarTaller(Integer.parseInt(request.getParameter("0")), // id
            request.getParameter("1"), // nombre
            request.getParameter("2"), // descripcin
            request.getParameter("3"), // fin registro (Fecha hasta donde est permitido registrarse)
            request.getParameter("4"), // inicio del taller
            Integer.parseInt(request.getParameter("5")), // costo
            Integer.parseInt(request.getParameter("6")) // cupos
    );//from   w w w  .j av  a  2s  .  c  om

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    if (r.get(0) == "error") {
        JSONObject obj = new JSONObject();
        obj.put("isError", true);
        obj.put("errorDescrip", r.get(1));
        out.print(obj);
    } else if (r.get(0) == "isExitoso") {
        JSONObject obj = new JSONObject();
        obj.put("Exitoso", true);
        out.print(obj);
    } else
        Util.errordeRespuesta(r, out);
}

From source file:org.ngrinder.script.controller.DavSvnController.java

/**
 * Handler for error.//from  ww w . j  a  va2  s.c om
 * 
 * @param error
 *            error occurred
 * @param servletResponse
 *            response
 * @throws IOException
 *             occurs when IO has problem
 */
public static void handleError(DAVException error, HttpServletResponse servletResponse) throws IOException {
    SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, error);
    DAVResponse response = error.getResponse();
    if (response == null) {
        DAVException stackErr = error;
        while (stackErr != null && stackErr.getTagName() == null) {
            stackErr = stackErr.getPreviousException();
        }

        if (stackErr != null && stackErr.getTagName() != null) {
            servletResponse.setContentType(XML_CONTENT_TYPE);
            servletResponse.setStatus(stackErr.getResponseCode());

            StringBuffer errorMessageBuffer = new StringBuffer();
            SVNXMLUtil.addXMLHeader(errorMessageBuffer);
            errorMessageBuffer.append('\n');
            errorMessageBuffer.append("<D:error xmlns:D=\"DAV:\"");

            if (stackErr.getMessage() != null) {
                errorMessageBuffer.append(" xmlns:m=\"http://apache.org/dav/xmlns\"");
            }

            if (stackErr.getNameSpace() != null) {
                errorMessageBuffer.append(" xmlns:C=\"");
                errorMessageBuffer.append(stackErr.getNameSpace());
                errorMessageBuffer.append("\">\n<C:");
                errorMessageBuffer.append(stackErr.getTagName());
                errorMessageBuffer.append("/>");
            } else {
                errorMessageBuffer.append(">\n<D:");
                errorMessageBuffer.append(stackErr.getTagName());
                errorMessageBuffer.append("/>");
            }

            if (stackErr.getMessage() != null) {
                errorMessageBuffer.append("<m:human-readable errcode=\"");
                errorMessageBuffer.append(stackErr.getErrorID());
                errorMessageBuffer.append("\">\n");
                errorMessageBuffer.append(SVNEncodingUtil.xmlEncodeCDATA(stackErr.getMessage()));
                errorMessageBuffer.append('\n');
                errorMessageBuffer.append("</m:human-readable>\n");
            }
            errorMessageBuffer.append("</D:error>\n");
            servletResponse.getWriter().print(errorMessageBuffer.toString());
            SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, errorMessageBuffer.toString());
            return;
        }
        servletResponse.setStatus(error.getResponseCode());
        return;
    }

    DAVXMLUtil.sendMultiStatus(response, servletResponse, error.getResponseCode(), null);
}

From source file:com.vmware.identity.SharedUtils.java

/**
 * Build mock HttpServletResponse object with a StringWriter
 *  which receives actual response/*www.  j  a v a 2s . c  o m*/
 * @param sw
 * @param contentType
 * @param expectCookie
 * @return
 * @throws IOException
 */
public static HttpServletResponse buildMockResponseSuccessObject(StringWriter sw, String contentType,
        boolean expectCookie, String contentDispositionValue) throws IOException {
    HttpServletResponse response = createMock(HttpServletResponse.class);
    if (expectCookie) {
        response.addCookie(isA(Cookie.class));
    }
    response.setContentType(contentType);
    if (contentDispositionValue != null && !contentDispositionValue.isEmpty()) {
        response.setHeader("Content-Disposition", contentDispositionValue);
    }
    expect(response.getWriter()).andReturn(new PrintWriter(sw)).anyTimes();
    replay(response);
    return response;
}

From source file:com.xqdev.jam.MLJAM.java

private static void sendServerProblemResponse(HttpServletResponse res, String s) throws IOException {
    // Commenting out the status code because we want the client to eval the error() call
    //res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    res.setContentType("x-marklogic/xquery; charset=UTF-8");
    if (s != null && s.length() > 4096) { // Cap super long errors
        s = s.substring(0, 2048) + " ...[trimmed]... " + s.substring(s.length() - 2048);
    }/*from  ww w . j a  va2 s  .  c  o  m*/
    Writer writer = res.getWriter();
    writer.write("error('" + escapeSingleQuotes(s) + "')");
    writer.flush();
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Admin.CRUDUsuarios.java

protected static void editarUsuario(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println(request.getParameter("5"));
    ArrayList r = CtrlAdmin.editarUsuario(Integer.parseInt(request.getParameter("0")), //IdUsuario
            request.getParameter("1"), //Nombre
            request.getParameter("2"), //Apellidos
            request.getParameter("3"), //Tipo de documento
            request.getParameter("4"), //documento
            request.getParameter("5"), //Correo= usuario
            request.getParameter("6"), //passworld
            request.getParameter("7").charAt(0)//rol
    );//from   w ww. ja  va 2 s .  co m

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    JSONObject obj = new JSONObject();
    if (r.get(0) == "error") {
        obj.put("isError", true);
        boolean errorSerio = false;
        if (r.get(1) == "usuario") {
            obj.put("errorDescrip", "El usuario ya existe");
        } else if (r.get(1) == "contrasena") {
            obj.put("errorDescrip", "La contrasea es invalida");
        } else if (r.get(1) == "documento") {
            obj.put("errorDescrip", "El documento ya est registrado");
        } else if (r.get(1) == "tipoDocumento") {
            obj.put("errorDescrip", "El tipo de documento es invalido");
        } else if (r.get(1) == "correo") {
            obj.put("errorDescrip", "El correo ya est registrado");
        } else if (r.get(1) == "correo1") {
            obj.put("errorDescrip", "El correo no es valido");
        } else if (r.get(1) == "nombre") {
            obj.put("errorDescrip", "Los nombres o apellidos son incorrectos");
        } else if (r.get(1) == "rol") {
            obj.put("errorDescrip", "El rol es invalido, los posibles valores son: E, P y A");
        } else {
            Util.errordeRespuesta(r, out);
            errorSerio = true;
        }
        if (!errorSerio) {
            out.print(obj);
        }
    } else if (r.get(0) == "isExitoso") {
        obj.put("Exitoso", true);
        out.print(obj);
    } else
        Util.errordeRespuesta(r, out);
}

From source file:com.wxxr.nirvana.json.JSONUtil.java

public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    if (StringUtils.isNotBlank(serializationParams.getSerializedJSON()))
        stringBuilder.append(serializationParams.getSerializedJSON());

    if (StringUtils.isNotBlank(serializationParams.getWrapPrefix()))
        stringBuilder.insert(0, serializationParams.getWrapPrefix());
    else if (serializationParams.isWrapWithComments()) {
        stringBuilder.insert(0, "/* ");
        stringBuilder.append(" */");
    } else if (serializationParams.isPrefix())
        stringBuilder.insert(0, "{}&& ");

    if (StringUtils.isNotBlank(serializationParams.getWrapSuffix()))
        stringBuilder.append(serializationParams.getWrapSuffix());

    String json = stringBuilder.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("[JSON]" + json);
    }/*from w  w  w . j  a v a 2 s. c  o m*/

    HttpServletResponse response = serializationParams.getResponse();

    // status or error code
    if (serializationParams.getStatusCode() > 0)
        response.setStatus(serializationParams.getStatusCode());
    else if (serializationParams.getErrorCode() > 0)
        response.sendError(serializationParams.getErrorCode());

    // content type
    response.setContentType(
            serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding());

    if (serializationParams.isNoCache()) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
    }

    if (serializationParams.isGzip()) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes(serializationParams.getEncoding()));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(serializationParams.getEncoding()).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:elw.web.ControllerElw.java

public static void storeContentHeaders(final FileBase fileBase, final HttpServletResponse resp) {
    final FileType fileType = IdNamed._.one(fileBase.getFileType());
    final String contentType;
    if (!fileType.getContentTypes().isEmpty()) {
        contentType = fileType.getContentTypes().get(0);
    } else {//  w w w.ja  va  2s  . c  o m
        contentType = fileType.isBinary() ? "binary/octet-stream" : "text/plain";
    }

    if (fileType.isBinary()) {
        resp.setContentType(contentType);
    } else {
        resp.setContentType(contentType + "; charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
    }

    resp.setContentLength(fileBase.getCouchFile(FileBase.CONTENT).getLength().intValue());
    resp.setHeader("Content-Disposition", "attachment;");
}