Example usage for javax.servlet.http HttpServletRequest getContentType

List of usage examples for javax.servlet.http HttpServletRequest getContentType

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getContentType.

Prototype

public String getContentType();

Source Link

Document

Returns the MIME type of the body of the request, or null if the type is not known.

Usage

From source file:forseti.admon.JAdmAWSS3Dlg.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.doPost(request, response);

    String adm_awss3_dlg = "";
    request.setAttribute("adm_awss3_dlg", adm_awss3_dlg);
    String mensaje = "";
    short idmensaje = -1;

    if (request.getContentType() != null
            && request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1) {
        if (!getSesion(request).getRegistrado()) {
            irApag("/forsetiadmin/errorAtributos.jsp", request, response);
            return;
        } else {//  w w  w.  j  a  va 2 s.co m
            if (!getSesion(request).getPermiso("ADM_AWSS3_GESTIONAR")) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", "ADM_AWSS3_GESTIONAR");
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                        "ADM_AWSS3_GESTIONAR", "AAS3||||", mensaje);
                irApag("/forsetiaweb/caja_mensajes.jsp", request, response);
                return;
            }

            try {
                JGestionArchivos gestion = new JGestionArchivos();
                DiskFileUpload fu = new DiskFileUpload();
                List items = fu.parseRequest(request);
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("ID_MODULO"))
                            gestion.setID_MODULO(item.getString());
                        else if (item.getFieldName().equals("OBJIDS"))
                            gestion.setOBJIDS(item.getString());
                        else if (item.getFieldName().equals("IDSEP"))
                            gestion.setIDSEP(item.getString());
                    } else
                        gestion.getArchivos().addElement(item);
                }

                if (!getSesion(request).getPermiso(gestion.getID_MODULO())) {
                    idmensaje = 3;
                    mensaje += MsjPermisoDenegado(request, "CEF", "ADM_AWSS3_GESTIONAR");
                    getSesion(request).setID_Mensaje(idmensaje, mensaje);
                    RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                            "ADM_AWSS3_GESTIONAR", "AAS3||||", mensaje);
                    irApag("/forsetiaweb/caja_mensajes.jsp", request, response);
                    return;
                }

                SubirArchivo(request, response, gestion);
                return;
            } catch (FileUploadException e) {
                e.printStackTrace();
                return;
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }

        }

    }

    if (request.getParameter("proceso") != null && !request.getParameter("proceso").equals("")) {
        if (request.getParameter("proceso").equals("SUBIR_ARCHIVO")) {
            // Revisa si tiene permisos
            if (!getSesion(request).getPermiso("ADM_AWSS3_GESTIONAR")) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", "ADM_AWSS3_GESTIONAR");
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                        "ADM_AWSS3_GESTIONAR", "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                return;
            }

            if (!getSesion(request).getPermiso(request.getParameter("ID_MODULO"))) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", request.getParameter("ID_MODULO"));
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                        "ADM_AWSS3_GESTIONAR", "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes_vsta.jsp", request, response);
                return;
            }

            getSesion(request).setID_Mensaje(idmensaje, mensaje);
            irApag("/forsetiweb/administracion/adm_awss3_dlg.jsp", request, response);
            return;

        } else if (request.getParameter("proceso").equals("DESCARGAR_ARCHIVO")) {
            if (!getSesion(request).getPermiso("ADM_AWSS3")) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", "ADM_AWSS3");
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADM_AWSS3",
                        "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                return;
            }

            if (!getSesion(request).getPermiso(request.getParameter("ID_MODULO"))) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", request.getParameter("ID_MODULO"));
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADM_AWSS3",
                        "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes_vsta.jsp", request, response);
                return;
            }
            // Solicitud de envio a procesar
            if (request.getParameter("id") != null) {
                String[] valoresParam = request.getParameterValues("id");
                if (valoresParam.length == 1) {
                    // Verificacion
                    Descargar(request, response, request.getParameter("id"));
                    return;
                } else {
                    idmensaje = 1;
                    mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 2);
                    getSesion(request).setID_Mensaje(idmensaje, mensaje);
                    irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                    return;
                }
            } else {
                idmensaje = 3;
                mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 1);
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                return;
            }
        } else if (request.getParameter("proceso").equals("ELIMINAR_ARCHIVO")) {
            // Revisa si tiene permisos
            if (!getSesion(request).getPermiso("ADM_AWSS3_GESTIONAR")) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", "ADM_AWSS3_GESTIONAR");
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                        "ADM_AWSS3_GESTIONAR", "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                return;
            }

            if (!getSesion(request).getPermiso(request.getParameter("ID_MODULO"))) {
                idmensaje = 3;
                mensaje += MsjPermisoDenegado(request, "CEF", request.getParameter("ID_MODULO"));
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                RDP("CEF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(),
                        "ADM_AWSS3_GESTIONAR", "AAS3|||", mensaje);
                irApag("/forsetiweb/caja_mensajes_vsta.jsp", request, response);
                return;
            }

            // Solicitud de envio a procesar
            if (request.getParameter("id") != null) {
                String[] valoresParam = request.getParameterValues("id");
                if (valoresParam.length == 1) {
                    //System.out.println("POST:" + request.getParameter("id") + ":request.getParameter(id)");
                    Eliminar(request, response, request.getParameter("id"));
                    return;
                } else {
                    idmensaje = 1;
                    mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 2);
                    getSesion(request).setID_Mensaje(idmensaje, mensaje);
                    irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                    return;
                }
            } else {
                idmensaje = 3;
                mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 1);
                getSesion(request).setID_Mensaje(idmensaje, mensaje);
                irApag("/forsetiweb/caja_mensajes.jsp", request, response);
                return;
            }
        } else {
            idmensaje = 3;
            mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 3);
            getSesion(request).setID_Mensaje(idmensaje, mensaje);
            irApag("/forsetiweb/caja_mensajes.jsp", request, response);
            return;
        }

    } else // si no se mandan parametros, manda a error
    {
        idmensaje = 3;
        mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 3);
        getSesion(request).setID_Mensaje(idmensaje, mensaje);
        irApag("/forsetiweb/caja_mensajes.jsp", request, response);
        return;
    }

}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.MultiContentServlet.java

/**
 * Handles the HTTP/*ww w .  j a  v  a  2  s.  c  o m*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter writer = null;
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        writer = response.getWriter();
    } catch (IOException ex) {
        log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);

    if (isMultiPart) {
        log("Content-Type: " + request.getContentType());
        // Create a factory for disk-based file items
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

        List items = null;

        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        ListIterator li = items.listIterator();

        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                if (debug) {
                    processFormField(fileItem);
                }
            } else {
                writer.print(processUploadedFile(fileItem));
            }
        }
    }

    if ("application/octet-stream".equals(request.getContentType())) {
        log("Content-Type: " + request.getContentType());
        String filename = request.getHeader("X-File-Name");

        try {
            is = request.getInputStream();
            fos = new FileOutputStream(new File(realPath + filename));
            IOUtils.copy(is, fos);
            response.setStatus(HttpServletResponse.SC_OK);
            writer.print("{success: true}");
        } catch (FileNotFoundException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
        } catch (IOException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
        } finally {
            try {
                fos.close();
                is.close();
            } catch (IOException ignored) {
            }
        }

        writer.flush();
        writer.close();
    }
}

From source file:org.eclipse.dirigible.runtime.registry.RepositoryServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String repositoryPath = null;
    final OutputStream out = response.getOutputStream();
    try {/*from  www  .  j a v  a  2s .  c  om*/
        repositoryPath = extractRepositoryPath(request);
        IEntity entity = getEntity(repositoryPath, request);
        byte[] data;
        if (entity == null) {
            ByteArrayOutputStream buff = new ByteArrayOutputStream();
            IOUtils.copy(request.getInputStream(), buff);
            data = buff.toByteArray();
            String contentType = request.getContentType();
            if (contentType == null) {
                contentType = "text/plain"; //$NON-NLS-1$
            }
            boolean isBinary = ContentTypeHelper.isBinary(contentType);
            getRepository(request).createResource(repositoryPath, data, isBinary, contentType);
        } else {
            if (entity instanceof IResource) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        THERE_IS_AN_EXISTING_RESOURCE_AT_THE_SAME_LOCATION_USE_PUT_METHOD_FOR_UPDATE);
            } else if (entity instanceof ICollection) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        THERE_IS_AN_EXISTING_COLLECTION_AT_THE_SAME_LOCATION);
            }
        }
    } catch (IllegalArgumentException ex) {
        logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    } catch (MissingResourceException ex) {
        logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_NO_CONTENT, ex.getMessage());
    } finally {
        out.flush();
        out.close();
    }

}

From source file:admin.controller.ServletEditCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w . j av  a2 s.c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        upload_path = AppConstants.ORG_CATEGORIES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("category_name")) {
                        category_name = fi.getString();
                    }
                    if (field_name.equals("category_id")) {
                        category_id = fi.getString();
                    }
                    if (field_name.equals("organization")) {
                        organization_id = fi.getString();
                        upload_path = upload_path + File.separator + organization_id;
                    }

                } else {
                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(upload_path);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = file_name.indexOf(".");
                        //                            String Str = file_name.substring(0, inStr);
                        //
                        //                            file_name = category_name + "_" + Str + ".jpeg";
                        file_name = category_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String filePath = upload_path + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                }
            }
            categories.editCategories(Integer.parseInt(category_id), Integer.parseInt(organization_id),
                    category_name, file_name);
            response.sendRedirect(request.getContextPath() + "/admin/categories.jsp");
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while editing categories", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

From source file:com.sap.dirigible.runtime.registry.RepositoryServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String repositoryPath = null;
    final OutputStream out = response.getOutputStream();
    try {//from  ww w  .  j a  v  a  2  s. co  m
        repositoryPath = extractRepositoryPath(request);
        IEntity entity = getEntity(repositoryPath, request);
        byte[] data;
        if (entity == null) {
            ByteArrayOutputStream buff = new ByteArrayOutputStream();
            IOUtils.copy(request.getInputStream(), buff);
            data = buff.toByteArray();
            String contentType = request.getContentType();
            if (contentType == null) {
                contentType = "text/plain"; //$NON-NLS-1$
            }
            boolean isBinary = ContentTypeHelper.isBinary(contentType);
            getRepository(request).createResource(repositoryPath, data, isBinary, contentType);
        } else {
            if (entity instanceof IResource) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        THERE_IS_AN_EXISTING_RESOURCE_AT_THE_SAME_LOCATION_USE_PUT_METHOD_FOR_UPDATE);
            } else if (entity instanceof ICollection) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        THERE_IS_AN_EXISTING_COLLECTION_AT_THE_SAME_LOCATION);
            }
        }
    } catch (IllegalArgumentException ex) {
        logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    } catch (MissingResourceException ex) {
        logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage());
        response.sendError(HttpServletResponse.SC_NO_CONTENT, ex.getMessage());
    } finally {
        out.flush();
        out.close();
    }

}

From source file:admin.controller.ServletAddPersonality.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w  w .j  a  v a 2  s  .  c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        String uploadPath = AppConstants.BRAND_IMAGES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File("/tmp"));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("brandname")) {
                        brand_name = fi.getString();
                    }
                    if (field_name.equals("look")) {
                        look_id = fi.getString();
                    }

                } else {
                    check = brand.checkAvailability(brand_name);

                    if (check == false) {
                        field_name = fi.getFieldName();
                        file_name = fi.getName();

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                                int inStr = file_name.indexOf(".");
                        //                                String Str = file_name.substring(0, inStr);
                        //                                file_name = brand_name + "_" + Str + ".jpeg";

                        file_name = brand_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String filePath = uploadPath + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);
                        brand.addBrands(brand_name, Integer.parseInt(look_id), file_name);

                        response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp");

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    } else {
                        response.sendRedirect(
                                request.getContextPath() + "/admin/brandpersonality.jsp?exist=exist");
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
        }
    }

}

From source file:admin.controller.ServletAddCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  ww  .j  av  a2  s  .c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        String uploadPath = AppConstants.ORG_CATEGORIES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("category_name")) {
                        category_name = fi.getString();
                    }
                    if (field_name.equals("organization")) {
                        organization_id = fi.getString();
                        uploadPath = uploadPath + File.separator + organization_id;
                    }

                } else {

                    field_name = fi.getFieldName();
                    file_name = fi.getName();
                    if (file_name != "") {
                        check = categories.checkAvailability(category_name, Integer.parseInt(organization_id));
                        if (check == false) {
                            File uploadDir = new File(uploadPath);
                            if (!uploadDir.exists()) {
                                uploadDir.mkdirs();
                            }

                            //we need to save file name directly
                            //                                int inStr = file_name.indexOf(".");
                            //                                String Str = file_name.substring(0, inStr);
                            //                                file_name = category_name + "_" + Str + ".jpeg";

                            file_name = category_name + "_" + file_name;
                            boolean isInMemory = fi.isInMemory();
                            long sizeInBytes = fi.getSize();

                            String filePath = uploadPath + File.separator + file_name;
                            File storeFile = new File(filePath);

                            fi.write(storeFile);
                            categories.addCategories(Integer.parseInt(organization_id), category_name,
                                    file_name);

                            out.println("Uploaded Filename: " + filePath + "<br>");
                            response.sendRedirect(request.getContextPath() + "/admin/categories.jsp");
                        } else {
                            response.sendRedirect(
                                    request.getContextPath() + "/admin/categories.jsp?exist=exist");
                        }
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while adding categories", ex);
    } finally {
        out.close();
    }
}

From source file:org.eclipse.rdf4j.http.server.repository.RepositoryController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String reqMethod = request.getMethod();
    String queryStr = request.getParameter(QUERY_PARAM_NAME);

    if (METHOD_POST.equals(reqMethod)) {
        String mimeType = HttpServerUtil.getMIMEType(request.getContentType());

        if (!(Protocol.FORM_MIME_TYPE.equals(mimeType) || Protocol.SPARQL_QUERY_MIME_TYPE.equals(mimeType))) {
            throw new ClientHTTPException(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported MIME type: " + mimeType);
        }// w ww  .  j  a va2  s  .  c o m

        if (Protocol.SPARQL_QUERY_MIME_TYPE.equals(mimeType)) {
            // The query should be the entire body
            try {
                queryStr = IOUtils.toString(request.getReader());
            } catch (IOException e) {
                throw new HTTPException(HttpStatus.SC_BAD_REQUEST, "Error reading request message body", e);
            }
            if (queryStr.isEmpty())
                queryStr = null;
        }
    } else if (METHOD_DELETE.equals(reqMethod)) {
        String repId = RepositoryInterceptor.getRepositoryID(request);
        logger.info("DELETE request invoked for repository '" + repId + "'");

        if (queryStr != null) {
            logger.warn("query supplied on repository delete request, aborting delete");
            throw new HTTPException(HttpStatus.SC_BAD_REQUEST,
                    "Repository delete error: query supplied with request");
        }

        if (SystemRepository.ID.equals(repId)) {
            logger.warn("attempted delete of SYSTEM repository, aborting");
            throw new HTTPException(HttpStatus.SC_FORBIDDEN, "SYSTEM Repository can not be deleted");
        }

        try {
            boolean success = repositoryManager.removeRepository(repId);
            if (success) {
                logger.info("DELETE request successfully completed");
                return new ModelAndView(EmptySuccessView.getInstance());
            } else {
                logger.error("error while attempting to delete repository '" + repId + "'");
                throw new HTTPException(HttpStatus.SC_BAD_REQUEST,
                        "could not locate repository configuration for repository '" + repId + "'.");
            }
        } catch (RDF4JException e) {
            logger.error("error while attempting to delete repository '" + repId + "'", e);
            throw new ServerHTTPException("Repository delete error: " + e.getMessage(), e);
        }
    }

    Repository repository = RepositoryInterceptor.getRepository(request);

    int qryCode = 0;
    if (logger.isInfoEnabled() || logger.isDebugEnabled()) {
        qryCode = String.valueOf(queryStr).hashCode();
    }

    boolean headersOnly = false;
    if (METHOD_GET.equals(reqMethod)) {
        logger.info("GET query {}", qryCode);
    } else if (METHOD_HEAD.equals(reqMethod)) {
        logger.info("HEAD query {}", qryCode);
        headersOnly = true;
    } else if (METHOD_POST.equals(reqMethod)) {
        logger.info("POST query {}", qryCode);
    }

    logger.debug("query {} = {}", qryCode, queryStr);

    if (queryStr != null) {
        RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request);
        try {
            Query query = getQuery(repository, repositoryCon, queryStr, request, response);

            View view;
            Object queryResult = null;
            FileFormatServiceRegistry<? extends FileFormat, ?> registry;

            try {
                if (query instanceof TupleQuery) {
                    if (!headersOnly) {
                        TupleQuery tQuery = (TupleQuery) query;
                        long limit = ProtocolUtil.parseLongParam(request, Protocol.LIMIT_PARAM_NAME, 0);
                        long offset = ProtocolUtil.parseLongParam(request, Protocol.OFFSET_PARAM_NAME, 0);
                        boolean distinct = ProtocolUtil.parseBooleanParam(request, Protocol.DISTINCT_PARAM_NAME,
                                false);

                        final TupleQueryResult tqr = distinct ? QueryResults.distinctResults(tQuery.evaluate())
                                : tQuery.evaluate();
                        queryResult = QueryResults.limitResults(tqr, limit, offset);
                    }
                    registry = TupleQueryResultWriterRegistry.getInstance();
                    view = TupleQueryResultView.getInstance();
                } else if (query instanceof GraphQuery) {
                    if (!headersOnly) {
                        GraphQuery gQuery = (GraphQuery) query;
                        long limit = ProtocolUtil.parseLongParam(request, Protocol.LIMIT_PARAM_NAME, 0);
                        long offset = ProtocolUtil.parseLongParam(request, Protocol.OFFSET_PARAM_NAME, 0);
                        boolean distinct = ProtocolUtil.parseBooleanParam(request, Protocol.DISTINCT_PARAM_NAME,
                                false);

                        final GraphQueryResult qqr = distinct ? QueryResults.distinctResults(gQuery.evaluate())
                                : gQuery.evaluate();
                        queryResult = QueryResults.limitResults(qqr, limit, offset);
                    }
                    registry = RDFWriterRegistry.getInstance();
                    view = GraphQueryResultView.getInstance();
                } else if (query instanceof BooleanQuery) {
                    BooleanQuery bQuery = (BooleanQuery) query;

                    queryResult = headersOnly ? null : bQuery.evaluate();
                    registry = BooleanQueryResultWriterRegistry.getInstance();
                    view = BooleanQueryResultView.getInstance();
                } else {
                    throw new ClientHTTPException(SC_BAD_REQUEST,
                            "Unsupported query type: " + query.getClass().getName());
                }
            } catch (QueryInterruptedException e) {
                logger.info("Query interrupted", e);
                throw new ServerHTTPException(SC_SERVICE_UNAVAILABLE, "Query evaluation took too long");
            } catch (QueryEvaluationException e) {
                logger.info("Query evaluation error", e);
                if (e.getCause() != null && e.getCause() instanceof HTTPException) {
                    // custom signal from the backend, throw as HTTPException
                    // directly (see SES-1016).
                    throw (HTTPException) e.getCause();
                } else {
                    throw new ServerHTTPException("Query evaluation error: " + e.getMessage());
                }
            }

            Object factory = ProtocolUtil.getAcceptableService(request, response, registry);

            Map<String, Object> model = new HashMap<String, Object>();
            model.put(QueryResultView.FILENAME_HINT_KEY, "query-result");
            model.put(QueryResultView.QUERY_RESULT_KEY, queryResult);
            model.put(QueryResultView.FACTORY_KEY, factory);
            model.put(QueryResultView.HEADERS_ONLY, headersOnly);
            model.put(QueryResultView.CONNECTION_KEY, repositoryCon);

            return new ModelAndView(view, model);
        } catch (Exception e) {
            // only close the connection when an exception occurs. Otherwise, the QueryResultView will take care of closing it.
            repositoryCon.close();
            throw e;
        }
    } else {
        throw new ClientHTTPException(SC_BAD_REQUEST, "Missing parameter: " + QUERY_PARAM_NAME);
    }
}

From source file:com.bstek.dorado.view.resolver.ViewServiceResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    XmlEscapeWriter writer = new XmlEscapeWriter(getWriter(request, response));

    JsonBuilder jsonBuilder = new JsonBuilder(writer);
    ServletInputStream in = request.getInputStream();
    DoradoContext context = DoradoContext.getCurrent();
    try {//from   ww  w  .ja va2 s  .co m
        String contentType = request.getContentType();
        if (contentType != null && contentType.contains(JAVASCRIPT_TOKEN)) {
            Reader reader = new InputStreamReader(in, Constants.DEFAULT_CHARSET);
            StringBuffer buf = new StringBuffer();
            char[] cs = new char[BUFFER_SIZE];
            for (int n; (n = reader.read(cs)) > 0;) {
                buf.append(new String(cs, 0, n));
            }

            ObjectNode objectNode = (ObjectNode) JsonUtils.getObjectMapper().readTree(buf.toString());

            processTask(writer, objectNode, context);
        } else if (contentType != null && contentType.contains(XML_TOKEN)) {
            Document document = getXmlDocumentBuilder(context)
                    .loadDocument(new InputStreamResource(in, request.getRequestURI()));

            writer.append("<?xml version=\"1.0\" encoding=\"" + Constants.DEFAULT_CHARSET + "\"?>\n");
            writer.append("<result>\n");

            Writer escapeWriter = new XmlEscapeWriter(writer);
            for (Element element : DomUtils.getChildElements(document.getDocumentElement())) {
                writer.append("<request>\n");
                writer.append("<response type=\"json\"><![CDATA[\n");
                writer.setEscapeEnabled(true);

                String textContent = DomUtils.getTextContent(element);

                ObjectNode objectNode = (ObjectNode) JsonUtils.getObjectMapper().readTree(textContent);
                try {
                    processTask(escapeWriter, objectNode, context);
                    writer.setEscapeEnabled(false);

                    writer.append("\n]]></response>\n");
                } catch (Exception e) {
                    Throwable t = e;
                    while (t.getCause() != null) {
                        t = t.getCause();
                    }
                    writer.setEscapeEnabled(false);

                    writer.append("\n]]></response>\n");
                    if (t instanceof ClientRunnableException) {
                        writer.append("<exception type=\"runnable\"><![CDATA[");
                        writer.setEscapeEnabled(true);
                        writer.append("(function(){").append(((ClientRunnableException) t).getScript())
                                .append("})");
                    } else {
                        writer.append("<exception><![CDATA[\n");
                        writer.setEscapeEnabled(true);
                        outputException(jsonBuilder, e);
                    }
                    writer.setEscapeEnabled(false);
                    writer.append("\n]]></exception>\n");
                    logger.error(e, e);
                }
                writer.append("</request>\n");
            }

            writer.append("</result>");
        }
    } catch (Exception e) {
        in.close();

        Throwable t = e;
        while (t.getCause() != null) {
            t = t.getCause();
        }

        if (t instanceof ClientRunnableException) {
            response.setContentType("text/runnable");
            writer.append("(function(){").append(((ClientRunnableException) t).getScript()).append("})");
        } else {
            response.setContentType("text/dorado-exception");
            outputException(jsonBuilder, e);
        }

        logger.error(e, e);
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:org.hdiv.filter.ValidatorFilter.java

/**
 * Called by the container each time a request/response pair is passed through the chain due to a client request for
 * a resource at the end of the chain.//  w  w w.  j  av a  2 s  . co m
 * 
 * @param request
 *            request object
 * @param response
 *            response object
 * @param filterChain
 *            filter chain
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 *      javax.servlet.FilterChain)
 */
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    this.initDependencies();

    ResponseWrapper responseWrapper = new ResponseWrapper(response);
    RequestWrapper requestWrapper = getRequestWrapper(request);

    HttpServletRequest multipartProcessedRequest = requestWrapper;

    try {

        boolean legal = false;
        boolean isMultipartException = false;

        if (this.isMultipartContent(request.getContentType())) {

            requestWrapper.setMultipart(true);

            try {

                if (this.multipartConfig == null) {
                    throw new RuntimeException(
                            "No 'multipartConfig' configured. It is required to multipart requests.");
                }

                multipartProcessedRequest = this.multipartConfig.handleMultipartRequest(requestWrapper,
                        super.getServletContext());

            } catch (HdivMultipartException e) {
                request.setAttribute(IMultipartConfig.FILEUPLOAD_EXCEPTION, e);
                isMultipartException = true;
                legal = true;
            }
        }

        ValidatorHelperResult result = null;
        if (!isMultipartException) {
            result = this.validationHelper.validate(multipartProcessedRequest);
            legal = result.isValid();
        }

        if (legal || this.hdivConfig.isDebugMode()) {
            processRequest(multipartProcessedRequest, responseWrapper, filterChain);
        } else {

            // Call to ValidatorErrorHandler
            this.errorHandler.handleValidatorError(multipartProcessedRequest, response, result.getErrorCode());
        }

    } catch (IOException e) {
        // Internal framework exception, rethrow exception
        throw e;
    } catch (ServletException e) {
        // Internal framework exception, rethrow exception
        throw e;
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Exception in request validation:");
            log.error("Message: " + e.getMessage());

            StringBuffer buffer = new StringBuffer();
            StackTraceElement[] trace = e.getStackTrace();
            for (int i = 0; i < trace.length; i++) {
                buffer.append("\tat " + trace[i] + System.getProperty("line.separator"));
            }
            log.error("StackTrace: " + buffer.toString());
            log.error("Cause: " + e.getCause());
            log.error("Exception: " + e.toString());
        }
        // Redirect to error page
        if (!this.hdivConfig.isDebugMode()) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + this.hdivConfig.getErrorPage()));
        }
    }
}