Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:com.eryansky.common.web.servlet.kindeditor.FileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String dirName = request.getParameter("dir");
    if (dirName == null) {
        dirName = "image";
    }//from  w  w w . java  2s.  com

    //?
    String uploadPath = getInitParameter("UPLOAD_PATH");
    if (StringUtils.isNotBlank(uploadPath)) {
        configPath = uploadPath;
    }

    if ("image".equals(dirName)) {

        //?
        Long size = Long.parseLong(getInitParameter("Img_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        //(?gif, jpg, jpeg, png, bmp)
        String type = getInitParameter("Img_YPES");
        if (StringUtils.isNotBlank(type)) {
            extMap.put("image", type);
        }

    } else {
        //?
        Long size = Long.parseLong(getInitParameter("File_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        if ("file".equals(dirName)) {
            //(doc, xls, ppt, pdf, txt, rar, zip)
            String type = getInitParameter("File_TYPES");
            if (StringUtils.isNotBlank(type)) {
                extMap.put("file", type);
            }
        }
    }

    if (StringUtils.isBlank(configPath)) {
        ServletUtils.renderText(getError("?!"), response);
        return;
    }

    //?
    String savePath = this.getServletContext().getRealPath("/") + configPath;

    //?URL
    String saveUrl = request.getContextPath() + "/" + configPath;

    if (!ServletFileUpload.isMultipartContent(request)) {
        ServletUtils.renderText(getError(""), response);
        return;
    }
    //
    File uploadDir = new File(savePath);
    if (!uploadDir.isDirectory()) {
        FileUtil.createDirectory(uploadDir.getPath());
        //         ServletUtils.rendText(getError("?"), response);
        //         return;
    }
    //??
    if (!uploadDir.canWrite()) {
        ServletUtils.renderText(getError("??"), response);
        return;
    }

    if (!extMap.containsKey(dirName)) {
        ServletUtils.renderText(getError("???"), response);
        return;
    }
    //
    savePath += dirName + "/";
    saveUrl += dirName + "/";
    File saveDirFile = new File(savePath);
    if (!saveDirFile.exists()) {
        saveDirFile.mkdirs();
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String ymd = sdf.format(new Date());
    savePath += ymd + "/";
    saveUrl += ymd + "/";
    File dirFile = new File(savePath);
    if (!dirFile.exists()) {
        dirFile.mkdirs();
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");

    try {
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            long fileSize = item.getSize();
            if (!item.isFormField()) {
                //?
                if (item.getSize() > maxSize) {
                    ServletUtils.renderText(getError("??"), response);
                    return;
                }
                //??
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    ServletUtils
                            .renderText(getError("??????\n??"
                                    + extMap.get(dirName) + "?"), response);
                    return;
                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try {
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                } catch (Exception e) {
                    ServletUtils.renderText(getError(""), response);
                    return;
                }

                Map<String, Object> obj = Maps.newHashMap();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);
                ServletUtils.renderText(obj, response);
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

}

From source file:ea.ejb.AbstractFacade.java

public Map<String, String> obtenerDatosFormConImagen(HttpServletRequest request) {

    Map<String, String> mapDatos = new HashMap();

    final String SAVE_DIR = "uploadImages";

    // Parametros del form
    String description = null;//w w  w .j  a va  2 s.  co  m
    String url_image = null;
    String id_grupo = null;

    boolean isMultiPart;
    String filePath;
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;
    File file = null;
    InputStream inputStream = null;
    OutputStream outputStream = null;

    // gets absolute path of the web application
    String appPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    filePath = appPath + File.separator + "assets" + File.separator + "img" + File.separator + SAVE_DIR;
    String filePathWeb = "assets/img/" + SAVE_DIR + "/";
    // creates the save directory if it does not exists
    File fileSaveDir = new File(filePath);

    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }
    // Check that we have a file upload request
    isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {

        // Parse the request
        List<FileItem> items = getMultipartItems(request);

        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        int offset = 0;
        int leidos = 0;
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                // ProcessFormField
                String name = item.getFieldName();
                String value = item.getString();
                if (name.equals("description_post_grupo") || name.equals("descripcion")) {
                    description = value;
                } else if (name.equals("id_grupo")) {
                    id_grupo = value;
                }
            } else {
                // ProcessUploadedFile
                try {
                    String itemName = item.getName();
                    if (!itemName.equals("")) {
                        url_image = filePathWeb + item.getName();
                        // read this file into InputStream
                        inputStream = item.getInputStream();
                        // write the inputStream to a FileOutputStream
                        if (file == null) {
                            String fileDirUpload = filePath + File.separator + item.getName();
                            file = new File(fileDirUpload);
                            // crea el archivo en el sistema
                            file.createNewFile();
                            if (file.exists()) {
                                outputStream = new FileOutputStream(file);
                            }
                        }

                        int read = 0;
                        byte[] bytes = new byte[1024];

                        while ((read = inputStream.read(bytes)) != -1) {
                            outputStream.write(bytes, offset, read);
                            leidos += read;
                        }
                        offset += leidos;
                        leidos = 0;
                        System.out.println("Done!");
                    } else {
                        url_image = "";
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        if (outputStream != null) {
            try {
                // outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    mapDatos.put("descripcion", description);
    mapDatos.put("imagen", url_image);
    mapDatos.put("id_grupo", id_grupo);

    return mapDatos;
}

From source file:ManageDatasetFiles.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w  w . j av  a 2 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        //get the dataset files
        //add more files
        //delete some files
        /* TODO output your page here. You may use following sample code. */
        String command = request.getParameter("command");
        String datasetid = request.getParameter("datasetid");
        //System.out.println("Hello World");
        //System.out.println(command);
        //System.out.println(studyid);
        if (command.equalsIgnoreCase("getDatasetFiles")) {
            //getting dataset files
            //first get the filenames in the directory.
            //I will get the list of files in this directory and send it

            String datasetPath = getServletContext().getRealPath("/datasets/" + datasetid);

            System.out.println(datasetid);
            File root = new File(datasetPath);
            File[] list = root.listFiles();

            ArrayList<String> fileItemList = new ArrayList<String>();
            if (list == null) {
                System.out.println("List is null");
                return;
            }

            for (File f : list) {
                if (f.isDirectory()) {
                    ArrayList<String> dirItems = getFileItems(f.getAbsolutePath(), f.getName());

                    for (int i = 0; i < dirItems.size(); i++) {
                        fileItemList.add(dirItems.get(i));
                    }

                } else {
                    System.out.println(f.getName());
                    fileItemList.add(f.getName());
                }
            }

            System.out.println("**** Printing the fileItems now **** ");
            String outputStr = "";
            for (int i = 0; i < fileItemList.size(); i++) {
                outputStr += fileItemList.get(i);
            }
            if (outputStr.length() > 1) {

                out.println(outputStr);
            }
        } else if (command.equalsIgnoreCase("addDatasetFiles")) {
            //add the files
            //get the files and add them

            String studyFolderPath = getServletContext().getRealPath("/datasets/" + datasetid);
            File studyFolder = new File(studyFolderPath);

            //process only if its multipart content
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
                    List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    int cnt = 0;
                    for (FileItem item : multiparts) {
                        if (!item.isFormField()) {
                            // cnt++;
                            String name = new File(item.getName()).getName();
                            //write the file to disk            
                            if (!studyFolder.exists()) {
                                studyFolder.mkdir();
                                System.out.println("The Folder has been created");
                            }
                            item.write(new File(studyFolder + File.separator + name));
                            System.out.println("File name is :: " + name);
                        }
                    }

                    System.out.print("Files successfully uploaded");
                } catch (Exception ex) {
                    //System.out.println("File Upload Failed due to " + ex);
                    System.out.print("File Upload Failed due to " + ex);
                }

            } else {
                // System.out.println("The request did not include files");
                System.out.println("The request did not include files");
            }

        } else if (command.equalsIgnoreCase("deleteDatasetFiles")) {
            //get the array of files and delete thems
            String[] mpk;

            //get the array of file-names
            mpk = request.getParameterValues("fileNames");
            for (int i = 0; i < mpk.length; i++) {
                String filePath = getServletContext().getRealPath("/datasets/" + datasetid + "/" + mpk[i]);

                System.out.println(filePath);
                File f = new File(filePath);
                f.delete();

            }
        }
        //out.println("</html>");
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:ai.ilikeplaces.servlets.GenericFileGrabber.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request__/*ww  w . j  ava 2s .  c om*/
 * @param response__
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
protected void processRequest(final HttpServletRequest request__, final HttpServletResponse response__)
        throws ServletException, IOException {

    Loggers.DEBUG.debug("Hello! Request on " + getClass().getName());

    final SmartLogger sl = SmartLogger.start(Loggers.LEVEL.USER, Loggers.CODE_GFG, 60000, null, true);

    response__.setContentType("text/html;charset=UTF-8");

    final PrintWriter out = response__.getWriter();

    try {
        fileUpload: {
            if (!isFileUploadPermitted()) {
                errorTemporarilyDisabled(out);
                break fileUpload;
            }
            stateSignedOn: {
                final HttpSession session = request__.getSession(false);

                breakIfNoLogin: {
                    if (session == null) {
                        sl.appendToLogMSG("No Login as in no session.");
                        sl.complete(Loggers.FAILED);
                        errorNoLogin(out);
                        break stateSignedOn;
                    } else if (session.getAttribute(ServletLogin.HumanUser) == null) {
                        sl.appendToLogMSG("No Login as in no HumanUser attribute");
                        sl.complete(Loggers.FAILED);
                        errorNoLogin(out);
                        break stateSignedOn;
                    }
                }
                processRequestType: {
                    /*Check that we have a file upload request*/
                    final boolean isMultipart = ServletFileUpload.isMultipartContent(request__);
                    if (!isMultipart) {
                        LoggerFactory.getLogger(ServletFileUploads.class.getName())
                                .error(logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0001"));
                        sl.appendToLogMSG("Not multipart request");
                        sl.complete(Loggers.FAILED);
                        errorNonMultipart(out);
                        break processRequestType;
                    }

                    @SuppressWarnings("unchecked")
                    final HumanUserLocal sBLoggedOnUserLocal = ((SessionBoundBadRefWrapper<HumanUserLocal>) session
                            .getAttribute(ServletLogin.HumanUser)).getBoundInstance();

                    try {
                        processRequest: {

                            // Create a new file upload handler
                            final ServletFileUpload upload = new ServletFileUpload();
                            // Parse the request
                            FileItemIterator iter = upload.getItemIterator(request__);
                            boolean persisted = false;

                            Return<File> r = processFileUploadRequest(iter, session);
                            persisted = r.returnStatus() == 0;
                            if (!persisted) {
                                sl.appendToLogMSG(r.returnMsg());
                                sl.complete(Loggers.FAILED);
                                errorReorderedSomethingWentWrong(out, r.returnMsg());
                                break processRequest;
                            } else {
                                sl.appendToLogMSG(r.returnMsg());
                                sl.complete(Loggers.DONE);
                                successFileName(out, r.returnMsg(), r.returnMsg());
                                break processRequest;
                            }
                        }

                    } catch (FileUploadException ex) {
                        Loggers.EXCEPTION.error(null, ex);
                        errorBusy(out);
                    }
                }

            }

        }
    } catch (final Throwable t_) {
        Loggers.EXCEPTION.error("SORRY! I ENCOUNTERED AN EXCEPTION DURING THE FILE UPLOAD", t_);
    }

}

From source file:application.controllers.admin.EmotionList.java

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

    //upload image to browser for add emotions
    //upload image to browser for add emotions
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();/* w  ww  .j a  v  a2  s  .c  o  m*/
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE);
    upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // String uploadPath = Registry.get("Host") +"/emotions-image/"+ UPLOAD_DIRECTORY;
    String uploadPath = Registry.get("imageHost") + "/emotions-image/" + UploadConstant.UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    //list image user upload
    String[] arrLinkImage = null;
    try {
        int indexImage = 0;
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        arrLinkImage = new String[formItems.size()];
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String extensionImage = "";
                for (int i = fileName.length() - 1; i >= 0; i--) {
                    if (fileName.charAt(i) == '.') {
                        break;

                    } else {
                        extensionImage = fileName.charAt(i) + extensionImage;
                    }
                }
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                String fieldName = item.getFieldName();

                // saves the file on disk
                item.write(storeFile);
                arrLinkImage[indexImage++] = item.getName();
            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    //   request.setAttribute("arrLinkImage", arrLinkImage);
    //  RequestDispatcher rd = request.getRequestDispatcher("/groupEmotion/emotion/add");
    //   rd.forward(request, response);
    //        String sessionId = request.getAttribute("sessionIdAdmin").toString();
    String sessionId = request.getSession().toString();
    String groupId = request.getParameter("groupId");
    Memcached.set("arrLinkImage-" + sessionId, 3600, arrLinkImage);

    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    response.setHeader("Location", Registry.get("Host") + "/groupEmotion/emotion/add?groupId=" + groupId);
    response.setContentType("text/html");

}

From source file:com.truthbean.core.web.kindeditor.FileUpload.java

@Override
public void service(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {

    final PageContext pageContext;
    HttpSession session = null;//  w w w.j  a v a  2 s.com
    final ServletContext application;
    final ServletConfig config;
    JspWriter out = null;
    final Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
        response.setContentType("text/html; charset=UTF-8");
        pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");

        /**
         * KindEditor JSP
         *
         * JSP???? ??
         *
         */
        // ?
        String savePath = pageContext.getServletContext().getRealPath("/") + "resource/";

        String savePath$ = savePath;

        // ?URL
        String saveUrl = request.getContextPath() + "/resource/";

        // ???
        HashMap<String, String> extMap = new HashMap<>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        // ?
        long maxSize = 10 * 1024 * 1024 * 1024L;

        response.setContentType("text/html; charset=UTF-8");

        if (!ServletFileUpload.isMultipartContent(request)) {
            out.println(getError(""));
            return;
        }
        // 
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            out.println(getError("?"));
            return;
        }
        // ??
        if (!uploadDir.canWrite()) {
            out.println(getError("??"));
            return;
        }

        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }
        if (!extMap.containsKey(dirName)) {
            out.println(getError("???"));
            return;
        }
        // 
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            if (!item.isFormField()) {
                // ?
                if (item.getSize() > maxSize) {
                    out.println(getError("??"));
                    return;
                }
                // ??
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    out.println(getError("??????\n??"
                            + extMap.get(dirName) + "?"));
                    return;
                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try {
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                } catch (Exception e) {
                    out.println(getError(""));
                    return;
                }

                JSONObject obj = new JSONObject();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);

                request.getSession().setAttribute("fileName", savePath$ + fileName);
                request.getSession().setAttribute("filePath", savePath + newFileName);
                request.getSession().setAttribute("fileUrl", saveUrl + newFileName);

                out.println(obj.toJSONString());
            }
        }

        out.write('\r');
        out.write('\n');
    } catch (IOException | FileUploadException t) {
        if (!(t instanceof javax.servlet.jsp.SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0) {
                if (response.isCommitted()) {
                    out.flush();
                } else {
                    out.clearBuffer();
                }
            }
            if (_jspx_page_context != null) {
                _jspx_page_context.handlePageException(t);
            } else {
                throw new ServletException(t);
            }
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:edu.fullerton.ldvw.LdvDispatcher.java

/**
 * Calls the appropriate module to handle the action requested by the user.
 * Note: most actions build the output in the vpage variable passed to pretty much everybody 
 *       However some module send data directly to the browser such as data or image downloads.
 *       That's what the return value specifies
 * @return true if our caller is responsible for sending html to the client.  False if we already did it
 * @throws WebUtilException we repackage any exceptions for consistent error handling.
 * @throws java.sql.SQLException/*from   ww w .  ja  v  a2 s .  c om*/
 * @throws edu.fullerton.ldvjutils.LdvTableException
 */
public boolean dispatchCommand() throws WebUtilException, SQLException, LdvTableException {
    boolean ret = true;

    helpManager = new HelpManager(db, vpage, vuser);
    helpManager.setContextPath(contextPath);
    helpManager.setServletPath(servletPath);
    helpManager.setParamMap(paramMap);

    addNavBar();

    if (request.getMethod().equalsIgnoreCase("post") && ServletFileUpload.isMultipartContent(request)) {

    } else {
        String act;
        act = request.getParameter("act");
        act = act == null ? "basechan" : act;
        act = act.toLowerCase();
        switch (act) {
        case "basechan":
            baseChan();
            break;
        case "chanlist":
            chanList();
            break;
        case "channelstats":
            channelStats();
            break;
        case "contactus":
            contactForm();
            break;
        case "contactsubmit":
            sendRpt();
            break;
        case "dbstats":
            if (vuser.isAdmin()) {
                dbStats();
            }
            break;
        case "defineplugin":
            definePlugin();
            break;
        case "doplot":
            ret = doPlot();
            break;
        case "edithelp":
            if (vuser.isAdmin()) {
                ret = editHelp();
            }
            break;
        case "getimg":
            ret = getImg();
            break;
        case "getjson":
            ret = getJson();
            break;
        case "gwpy-info":
            ret = gwpyInfo();
            break;
        case "imagehistory":
            imageHistory();
            break;
        case "singlechan":
            singleChan();
            break;
        case "ndshistory":
            ndsHistory();
            break;
        case "ndsstatus":
            ndsStatus();
            break;
        case "procsrvfrm":
            if (vuser.isAdmin()) {
                serverManager();
            }
            break;
        case "referenceplot":
            referencePlot();
            break;
        case "savehelptext":
            saveHelpText();
            break;
        case "servermanager":
            if (vuser.isAdmin()) {
                serverManager();
            }
            break;
        case "specialplot":
            vpage.setTitle("Special Plots");
            PluginManager pmanage = new PluginManager(db, vpage, vuser, paramMap);
            pmanage.setContextPath(contextPath);
            pmanage.setServletPath(servletPath);
            ret = pmanage.specialPlot();
            break;
        case "stats":
            if (vuser.isAdmin()) {
                userStats();
            }
            break;
        case "upload":
            uploadFiles();
            break;
        default:
            vpage.addLine(String.format("Unknow action requested: [%1$s]", act));
            break; // just in case somebody adds something after this
        }
    }
    return ret; // NB: ret is a boolean that says content is in vpage to be sent
    // otherwise we already sent a different mime type, like an image or pdf
}

From source file:com.ikon.servlet.admin.CssServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    updateSessionManager(request);// ww  w. j  a  v a  2 s . c  om

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Css css = new Css();
            css.setActive(false);

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("css_id")) {
                        if (!item.getString("UTF-8").isEmpty()) {
                            css.setId(new Long(item.getString("UTF-8")).longValue());
                        }
                    } else if (item.getFieldName().equals("css_name")) {
                        css.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("css_context")) {
                        css.setContext(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("css_content")) {
                        css.setContent(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("css_active")) {
                        css.setActive(true);
                    }
                }
            }

            if (action.equals("edit")) {
                CssDAO.getInstance().update(css);

                // Activity log
                UserActivity.log(userId, "ADMIN_CSS_UPDATE", String.valueOf(css.getId()), null, css.getName());
            } else if (action.equals("delete")) {
                String name = WebUtils.getString(request, "css_name");
                CssDAO.getInstance().delete(css.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_CSS_DELETE", String.valueOf(css.getId()), null, name);
            } else if (action.equals("create")) {
                long id = CssDAO.getInstance().create(css);

                // Activity log
                UserActivity.log(userId, "ADMIN_CSS_CREATE", String.valueOf(id), null, css.getName());
            }
        }

        list(userId, request, response);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:edu.lternet.pasta.portal.UploadEvaluateServlet.java

/**
 * The doPost method of the servlet. <br>
 * /*from  w  ww  .  j a v  a2  s .c  o m*/
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession httpSession = request.getSession();

    String uid = (String) httpSession.getAttribute("uid");

    if (uid == null || uid.isEmpty())
        uid = "public";

    String html = null;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

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

        // Parse the request
        try {

            List /* FileItem */ items = upload.parseRequest(request);

            // Process the uploaded items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {

                FileItem item = (FileItem) iter.next();

                if (!(item.isFormField())) {

                    File eml = processUploadedFile(item);

                    DataPackageManagerClient dpmClient = new DataPackageManagerClient(uid);
                    String xml = dpmClient.evaluateDataPackage(eml);

                    ReportUtility qrUtility = new ReportUtility(xml);
                    String htmlTable = qrUtility.xmlToHtmlTable(cwd + xslpath);

                    if (htmlTable == null) {
                        String msg = "The uploaded file could not be evaluated.";
                        throw new UserErrorException(msg);
                    } else {
                        html = HTMLHEAD + "<div class=\"qualityreport\">" + htmlTable + "</div>" + HTMLTAIL;
                    }

                }

            }

        } catch (Exception e) {
            handleDataPortalError(logger, e);
        }
    }

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.print(html);
    out.flush();
    out.close();
}

From source file:com.chrischurchwell.jukeit.server.ServerHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    Debug.debug("Handling Web Request: ", target);

    if (target.equalsIgnoreCase("/")) {

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);/*from   www. j ava2s. c om*/

        Template template = cfg.getTemplate("index.html");

        Map<String, Object> dataRoot = new HashMap<String, Object>();
        dataRoot.put("serverName", JukeIt.getInstance().getConfig().getString("serverName"));
        dataRoot.put("allowUpload", JukeIt.getInstance().getConfig().getBoolean("allowWebServerUploads"));

        dataRoot.put("files", JukeIt.getServerFileList());

        try {
            template.process(dataRoot, response.getWriter());
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return;
    }

    if (target.equalsIgnoreCase("/robots.txt")) {
        response.setContentType("text/plain;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);

        response.getWriter().println("User-agent: *");
        response.getWriter().println("Disallow: /");

        return;
    }

    if (target.equalsIgnoreCase("/upload")) {

        if (!JukeIt.getInstance().getConfig().getBoolean("allowWebServerUploads")) {
            return;
        }

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);

        if (!ServletFileUpload.isMultipartContent(request)) {
            response.getWriter().println("No File Upload Detected");
            return;
        }

        /* Straight from commons.io docs */

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

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

        // Parse the request
        try {

            List<FileItem> items = castList(FileItem.class, upload.parseRequest(request));

            // Process the uploaded items
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {
                    //processFormField(item);
                } else {
                    //processUploadedFile(item);
                    //String fieldName = item.getFieldName();
                    //String fileName = item.getName();
                    //String contentType = item.getContentType();
                    //boolean isInMemory = item.isInMemory();
                    //long sizeInBytes = item.getSize();

                    if (!item.getName().endsWith(".ogg") && !item.getName().endsWith(".wav")
                            && !item.getName().endsWith(".mp3")) {
                        response.getWriter().println("File must be a .ogg or .wave");
                        return;
                    }

                    String name = item.getName().replace(" ", "_");
                    File uploadedFile = new File(JukeIt.getInstance().getDataFolder(), "music/" + name);
                    item.write(uploadedFile);

                    response.getWriter().println("1");
                    return;
                }
            }

        } catch (FileUploadException e) {
            response.getWriter().println(e.getMessage());
            return;
        } catch (Exception e) {
            response.getWriter().println(e.getMessage());
            return;
        }

        return;
    }

}