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.nartex.FileManager.java

public FileManager(ServletContext servletContext, HttpServletRequest request) {
    // get document root like in php
    String contextPath = request.getContextPath();
    String documentRoot = servletContext.getRealPath("/").replaceAll("\\\\", "/");
    documentRoot = documentRoot.substring(0, documentRoot.indexOf(contextPath));

    this.referer = request.getHeader("referer");
    this.fileManagerRoot = documentRoot
            + referer.substring(referer.indexOf(contextPath), referer.indexOf("index.html"));

    // get uploaded file list
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    if (ServletFileUpload.isMultipartContent(request))
        try {//from www  . j av  a2  s  .  c o  m
            files = upload.parseRequest(request);
        } catch (Exception e) { // no error handling}
        }

    this.properties.put("Date Created", null);
    this.properties.put("Date Modified", null);
    this.properties.put("Height", null);
    this.properties.put("Width", null);
    this.properties.put("Size", null);

    // load config file
    loadConfig();

    if (config.getProperty("doc_root") != null)
        this.documentRoot = config.getProperty("doc_root");
    else
        this.documentRoot = documentRoot;

    dateFormat = new SimpleDateFormat(config.getProperty("date"));

    this.setParams();

    loadLanguageFile();
}

From source file:de.mpg.imeji.presentation.upload.UploadBean.java

public void upload() throws Exception {
    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();/*from ww w  .j  a v  a 2 s. c  o m*/
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (!item.isFormField()) {
                title = item.getName();
                StringTokenizer st = new StringTokenizer(title, ".");
                while (st.hasMoreTokens()) {
                    format = st.nextToken();
                }
                mimetype = "image/" + format;
                // TODO remove static image description
                description = "";
                try {
                    UserController uc = new UserController(null);
                    User user = uc.retrieve(getUser().getEmail());
                    try {
                        DepositController controller = new DepositController();
                        Item escidocItem = controller.createEscidocItem(stream, title, mimetype, format);
                        controller.createImejiImage(collection, user, escidocItem.getOriginObjid(), title,
                                URI.create(EscidocHelper.getOriginalResolution(escidocItem)),
                                URI.create(EscidocHelper.getThumbnailUrl(escidocItem)),
                                URI.create(EscidocHelper.getWebResolutionUrl(escidocItem)));
                        // controller.createImejiImage(collection, user, "escidoc:123", title,
                        // URI.create("http://imeji.org/test"), URI.create("http://imeji.org/test"),
                        // URI.create("http://imeji.org/test"));
                        sNum += 1;
                        sFiles.add(title);
                    } catch (Exception e) {
                        fNum += 1;
                        fFiles.add(title);
                        logger.error("Error uploading image: ", e);
                        // throw new RuntimeException(e);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        logger.info("Upload finished");
    }
}

From source file:com.openkm.extension.servlet.ZohoFileUploadServlet.java

@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("service({}, {})", request, response);
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    InputStream is = null;/*from  w w w. j  a  va  2s  . co m*/
    String id = "";

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

        // Parse the request and get all parameters and the uploaded file
        List<FileItem> items;

        try {
            items = upload.parseRequest(request);
            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();
                if (item.isFormField()) {
                    // if (item.getFieldName().equals("format")) { format =
                    // item.getString("UTF-8"); }
                    if (item.getFieldName().equals("id")) {
                        id = item.getString("UTF-8");
                    }
                    // if (item.getFieldName().equals("filename")) {
                    // filename = item.getString("UTF-8"); }
                } else {
                    is = item.getInputStream();
                }
            }

            // Retrieve token
            ZohoToken zot = ZohoTokenDAO.findByPk(id);

            // Save document
            if (Config.REPOSITORY_NATIVE) {
                String sysToken = DbSessionManager.getInstance().getSystemToken();
                String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode());
                new DbDocumentModule().checkout(sysToken, path, zot.getUser());
                new DbDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser());
            } else {
                String sysToken = JcrSessionManager.getInstance().getSystemToken();
                String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode());
                new JcrDocumentModule().checkout(sysToken, path, zot.getUser());
                new JcrDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser());
            }
        } catch (FileUploadException e) {
            log.error(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        } catch (DatabaseException e) {
            log.error(e.getMessage(), e);
        } catch (FileSizeExceededException e) {
            log.error(e.getMessage(), e);
        } catch (UserQuotaExceededException e) {
            log.error(e.getMessage(), e);
        } catch (VirusDetectedException e) {
            log.error(e.getMessage(), e);
        } catch (VersionException e) {
            log.error(e.getMessage(), e);
        } catch (LockException e) {
            log.error(e.getMessage(), e);
        } catch (AccessDeniedException e) {
            log.error(e.getMessage(), e);
        } catch (ExtensionException e) {
            log.error(e.getMessage(), e);
        } catch (AutomationException e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:com.mx.nibble.middleware.web.util.FileUploadOLD.java

public String execute() throws Exception {

    //ActionContext ac = invocation.getInvocationContext();

    HttpServletResponse response = ServletActionContext.getResponse();

    // MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest());
    HttpServletRequest multipartRequest = ServletActionContext.getRequest();

    List<FileItem> items2 = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartRequest);
    System.out.println("TAMAO ITEMS " + items2.size());
    System.out.println("Check that we have a file upload request");
    boolean isMultipart = ServletFileUpload.isMultipartContent(multipartRequest);
    System.out.println("isMultipart: " + isMultipart);

    String ourTempDirectory = "/opt/erp/import/obras/";

    byte[] cr = { 13 };
    byte[] lf = { 10 };
    String CR = new String(cr);
    String LF = new String(lf);
    String CRLF = CR + LF;/* ww w.  j  a  v  a  2s .  c  o  m*/
    System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF);

    //Initialization for chunk management.
    boolean bLastChunk = false;
    int numChunk = 0;

    //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL
    boolean generateError = false;
    boolean generateWarning = false;
    boolean sendRequest = false;

    response.setContentType("text/plain");

    java.util.Enumeration<String> headers = multipartRequest.getHeaderNames();
    System.out.println("[parseRequest.jsp]  ------------------------------ ");
    System.out.println("[parseRequest.jsp]  Headers of the received request:");
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        System.out.println("[parseRequest.jsp]  " + header + ": " + multipartRequest.getHeader(header));
    }
    System.out.println("[parseRequest.jsp]  ------------------------------ ");

    try {
        System.out.println(" Get URL Parameters.");
        Enumeration paraNames = multipartRequest.getParameterNames();
        System.out.println("[parseRequest.jsp]  ------------------------------ ");
        System.out.println("[parseRequest.jsp]  Parameters: ");
        String pname;
        String pvalue;
        while (paraNames.hasMoreElements()) {
            pname = (String) paraNames.nextElement();
            pvalue = multipartRequest.getParameter(pname);
            System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue);
            if (pname.equals("jufinal")) {
                System.out.println("pname.equals(\"jufinal\")");
                bLastChunk = pvalue.equals("1");
            } else if (pname.equals("jupart")) {
                System.out.println("pname.equals(\"jupart\")");
                numChunk = Integer.parseInt(pvalue);
            }

            //For debug convenience, putting error=true as a URL parameter, will generate an error
            //in this response.
            if (pname.equals("error") && pvalue.equals("true")) {
                generateError = true;
            }

            //For debug convenience, putting warning=true as a URL parameter, will generate a warning
            //in this response.
            if (pname.equals("warning") && pvalue.equals("true")) {
                generateWarning = true;
            }

            //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content
            //into the response of this page.
            if (pname.equals("sendRequest") && pvalue.equals("true")) {
                sendRequest = true;
            }

        }
        System.out.println("[parseRequest.jsp]  ------------------------------ ");

        int ourMaxMemorySize = 10000000;
        int ourMaxRequestSize = 2000000000;

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //The code below is directly taken from the jakarta fileupload common classes
        //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/
        ///////////////////////////////////////////////////////////////////////////////////////////////////////

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

        // Set factory constraints
        factory.setSizeThreshold(ourMaxMemorySize);
        factory.setRepository(new File(ourTempDirectory));

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

        // Set overall request size constraint
        upload.setSizeMax(ourMaxRequestSize);

        // Parse the request
        if (sendRequest) {
            //For debug only. Should be removed for production systems. 
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
            System.out.println("[parseRequest.jsp] Sending the received request content: ");
            InputStream is = multipartRequest.getInputStream();
            int c;
            while ((c = is.read()) >= 0) {
                System.out.write(c);
            } //while
            is.close();
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
        } else if (!multipartRequest.getContentType().startsWith("multipart/form-data")) {
            System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is "
                    + multipartRequest.getContentType());
        } else {
            List /* FileItem */ items = upload.parseRequest(multipartRequest);
            // Process the uploaded items
            Iterator iter = items.iterator();
            FileItem fileItem;
            File fout;
            System.out.println("[parseRequest.jsp]  Let's read the sent data   (" + items.size() + " items)");
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();

                if (fileItem.isFormField()) {
                    System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = "
                            + fileItem.getString());

                    //If we receive the md5sum parameter, we've read finished to read the current file. It's not
                    //a very good (end of file) signal. Will be better in the future ... probably !
                    //Let's put a separator, to make output easier to read.
                    if (fileItem.getFieldName().equals("md5sum[]")) {
                        System.out.println("[parseRequest.jsp]  ------------------------------ ");
                    }
                } else {
                    //Ok, we've got a file. Let's process it.
                    //Again, for all informations of what is exactly a FileItem, please
                    //have a look to http://jakarta.apache.org/commons/fileupload/
                    //
                    System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName());
                    System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName());
                    System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType());
                    System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize());
                    //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number.
                    String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : "");
                    fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName());
                    System.out.println("[parseRequest.jsp] File Out: " + fout.toString());
                    System.out.println(" write the file");
                    fileItem.write(fout);

                    //////////////////////////////////////////////////////////////////////////////////////
                    System.out.println(
                            " Chunk management: if it was the last chunk, let's recover the complete file");
                    System.out.println(" by concatenating all chunk parts.");
                    //
                    if (bLastChunk) {
                        System.out.println(
                                "[parseRequest.jsp]  Last chunk received: let's rebuild the complete file ("
                                        + fileItem.getName() + ")");
                        //First: construct the final filename.
                        FileInputStream fis;
                        FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName());
                        int nbBytes;
                        byte[] byteBuff = new byte[1024];
                        String filename;
                        for (int i = 1; i <= numChunk; i += 1) {
                            filename = fileItem.getName() + ".part" + i;
                            System.out.println("[parseRequest.jsp] " + "  Concatenating " + filename);
                            fis = new FileInputStream(ourTempDirectory + filename);
                            while ((nbBytes = fis.read(byteBuff)) >= 0) {
                                //out.println("[parseRequest.jsp] " + "     Nb bytes read: " + nbBytes);
                                fos.write(byteBuff, 0, nbBytes);
                            }
                            fis.close();
                        }
                        fos.close();
                    }

                    // End of chunk management
                    //////////////////////////////////////////////////////////////////////////////////////

                    fileItem.delete();
                }
            } //while
        }

        if (generateWarning) {
            System.out.println("WARNING: just a warning message.\\nOn two lines!");
        }

        System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :");

        //Let's wait a little, to simulate the server time to manage the file.
        Thread.sleep(500);

        //Do you want to test a successful upload, or the way the applet reacts to an error ?
        if (generateError) {
            System.out.println(
                    "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!");
        } else {
            System.out.println("SUCCESS");
            //out.println("                        <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>");
        }

        System.out.println("[parseRequest.jsp] " + "End of server treatment ");

    } catch (Exception e) {
        System.out.println("");
        System.out.println("ERROR: Exception e = " + e.toString());
        System.out.println("");
    }
    return SUCCESS;
}

From source file:com.ccsna.safetynet.NewsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  ww . ja  v 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");
    try {
        PrintWriter out = response.getWriter();
        String smallUrl = "", largeUrl = "", message = "", title = "", content = "", startDate = "",
                endDate = "", newsType = "", st = "", endTime = "", startTime = "", fileType = null;

        Date sDate = null, eDate = null;
        Time eTime = null, sTime = null;
        int action = 0, newsId = 0;
        boolean dataValid = true;
        News news = null;
        String fullPath = null;
        Member loggedInMember = UserAuthenticator.loggedInUser(request.getSession());
        if (loggedInMember != null) {
            String createdBy = String.valueOf(loggedInMember.getMemberId());
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            log.info("isMultipart :" + isMultipart);
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                String appPath = request.getServletContext().getRealPath("");

                //String glassfishInstanceRootPropertyName = "com.sun.aas.instanceRoot";
                //String instanceRoot = System.getProperty(glassfishInstanceRootPropertyName) + "/applications/user-pix/";
                try {
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (!item.isFormField()) {
                            //log.info("item is form field");
                            String fileName = item.getName();
                            //log.info("the name of the item is :" + fileName);
                            String contentType = item.getContentType();
                            //log.info("the content type is :" + contentType);
                            if (item.getContentType().equalsIgnoreCase(JPEG)
                                    || item.getContentType().equalsIgnoreCase(JPG)
                                    || item.getContentType().equalsIgnoreCase(PDF)) {
                                String root = appPath;
                                log.info("pdf content recognised");
                                log.info("root path is :" + appPath);
                                //String smallLoc = "/uploads/small";
                                String largeLoc = "/uploads/large";
                                log.info("largeLoc:" + largeLoc);
                                //File pathSmall = new File(root + smallLoc);
                                File pathLarge = new File(root + largeLoc);
                                //log.info("small image path :" + pathSmall);
                                log.info("large image path :" + pathLarge);
                                if (!pathLarge.exists()) {
                                    // boolean status = pathSmall.mkdirs();
                                    pathLarge.mkdirs();
                                }
                                if (item.getContentType().equalsIgnoreCase(PDF)) {
                                    log.info("loading pdf file");
                                    fileType = Menu.PDF;
                                    fileName = createdBy + "_" + System.currentTimeMillis() + "."
                                            + PDF_EXTENSION;

                                    //File uploadedFileSmall = new File(pathSmall + "/" + fileName);
                                    File uploadedFileLarge = new File(pathLarge + "/" + fileName);
                                    Menu.uploadPdfFile(item.getInputStream(), uploadedFileLarge);

                                } else {
                                    fileType = Menu.IMAGE;
                                    fileName = createdBy + "_" + System.currentTimeMillis() + "."
                                            + JPEG_EXTENSION;

                                    log.info("filename is : " + fileName);
                                    // File uploadedFileSmall = new File(pathSmall + "/" + fileName);
                                    File uploadedFileLarge = new File(pathLarge + "/" + fileName);
                                    //Menu.resizeImage(item.getInputStream(), 160, uploadedFileSmall);
                                    Menu.resizeImage(item.getInputStream(), 160, uploadedFileLarge);
                                }
                                //smallUrl = smallLoc + "/" + fileName + "";
                                largeUrl = largeLoc + "/" + fileName + "";
                                log.info("largeUrl image url is :" + largeUrl);

                                fullPath = request.getContextPath() + "/" + largeUrl;

                            }
                        } else {
                            if (item.getFieldName().equalsIgnoreCase("newsTitle")) {
                                title = item.getString();
                                log.info("title is :" + title);
                            }
                            if (item.getFieldName().equalsIgnoreCase("type")) {
                                newsType = item.getString();
                                log.info("newsType is :" + newsType);
                            }
                            if (item.getFieldName().equalsIgnoreCase("content")) {
                                content = item.getString();
                                log.info("content is :" + content);
                            }
                            if (item.getFieldName().equalsIgnoreCase("start_Date")) {
                                startDate = item.getString();
                                if (startDate != null && !startDate.isEmpty()) {
                                    sDate = Menu
                                            .convertDateToSqlDate(Menu.stringToDate(startDate, "yyyy-MM-dd"));
                                }
                                log.info("startDate is :" + startDate);
                            }
                            if (item.getFieldName().equalsIgnoreCase("end_Date")) {
                                endDate = item.getString();
                                if (endDate != null && !endDate.isEmpty()) {
                                    eDate = Menu.convertDateToSqlDate(Menu.stringToDate(endDate, "yyyy-MM-dd"));
                                }
                                log.info("endDate is :" + endDate);
                            }
                            if (item.getFieldName().equalsIgnoreCase("action")) {
                                action = Integer.parseInt(item.getString());
                                log.info("the action is :" + action);
                            }
                            if (item.getFieldName().equalsIgnoreCase("newsId")) {
                                newsId = Integer.parseInt(item.getString());
                                log.info("the newsid is :" + newsId);
                            }
                            if (item.getFieldName().equalsIgnoreCase("status")) {
                                st = item.getString();
                                log.info("the status is :" + st);
                            }
                            if (item.getFieldName().equalsIgnoreCase("end_Time")) {
                                endTime = item.getString();
                                if (endTime != null && !endTime.isEmpty()) {
                                    eTime = Menu.convertStringToSqlTime(endTime);
                                }
                                log.info("eTime is :" + eTime);

                            }

                            if (item.getFieldName().equalsIgnoreCase("start_Time")) {
                                startTime = item.getString();
                                if (startTime != null && !startTime.isEmpty()) {
                                    sTime = Menu.convertStringToSqlTime(startTime);
                                }
                                log.info("sTime is :" + sTime);

                            }
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
            }
            switch (Validation.Actions.values()[action]) {
            case CREATE:
                log.info("creating new serlvet ................"); {

                news = new NewsModel().addNews(title, newsType, content, sDate, eDate, new Date(), createdBy,
                        Menu.ACTIVE, largeUrl, fileType, fullPath);
            }
                if (news != null) {
                    log.info("news successfully created...");
                    message += "News item has been successfully added";
                    Validation.setAttributes(request, Validation.SUCCESS, message);
                    response.sendRedirect(request.getContextPath() + "/admin/management.jsp");
                } else {
                    log.info("news creating failed...");
                    message += "Unable to add news item";
                    Validation.setAttributes(request, Validation.ERROR, message);
                    response.sendRedirect(request.getContextPath() + "/admin/management.jsp");
                }
                break;
            case UPDATE:
                log.info("updating news ...");
                if (title != null && !title.isEmpty()) {
                    news = new NewsModel().findByParameter("title", title);
                }

                if (news != null && (news.getNewsId() == newsId)) {
                    log.info("news is :" + news.getNewsId());
                    dataValid = true;
                } else {
                    dataValid = false;
                }
                if (news == null) {
                    dataValid = true;
                }

                log.info("dataValid is :" + dataValid);

                if (dataValid) {
                    boolean newsUpdated = new NewsModel().updateNews(newsId, title, newsType, content, sDate,
                            eDate, createdBy, st, largeUrl, smallUrl, sTime, eTime);
                    if (newsUpdated) {
                        message += "News/Alert has been successfully updated";
                        Validation.setAttributes(request, Validation.SUCCESS, message);
                        response.sendRedirect(request.getContextPath() + "/admin/management.jsp");

                    } else {
                        message += "Unable to update news item";
                        Validation.setAttributes(request, Validation.ERROR, message);
                        response.sendRedirect(request.getContextPath() + "/admin/newsEdit.jsp?id=" + newsId);
                    }
                } else {
                    message += "News with same title already exist, Enter a different title";
                    Validation.setAttributes(request, Validation.ERROR, message);
                    response.sendRedirect(request.getContextPath() + "/admin/newsEdit.jsp?id=" + newsId);
                }
                break;
            }
        } else {
            message += "Session expired, Kindly login with username and password";
            Validation.setAttributes(request, Validation.ERROR, message);
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    } catch (Exception e) {

    }
}

From source file:it.unisa.tirocinio.servlet.studentUploadFiles.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  ww.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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Access-Control-Allow-Origin", "*");
    PrintWriter out = response.getWriter();
    HttpSession aSession = request.getSession();
    try {
        Person pers = (Person) aSession.getAttribute("person");
        String primaryKey = pers.getAccount().getEmail();
        PersonManager aPerson = PersonManager.getInstance();
        Person person = aPerson.getStudent(primaryKey);
        ConcreteStudentInformation aStudentInformation = ConcreteStudentInformation.getInstance();
        out = response.getWriter();

        String studentSubfolderPath = filePath + "/" + reverseSerialNumber(person.getMatricula());
        File subfolderFile = new File(studentSubfolderPath);
        if (!subfolderFile.exists()) {
            subfolderFile.mkdir();
        }

        isMultipart = ServletFileUpload.isMultipartContent(request);
        String serialNumber = null;
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        File fileToStore = null;
        String CVPath = "", ATPath = "";

        while (i.hasNext()) {

            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                if (fieldName.equals("cv")) {
                    fileToStore = new File(studentSubfolderPath + "/" + "CV.pdf");
                    CVPath = fileToStore.getAbsolutePath();
                } else if (fieldName.equals("doc")) {
                    fileToStore = new File(studentSubfolderPath + "/" + "ES.pdf");
                    ATPath = fileToStore.getAbsolutePath();
                }
                fi.write(fileToStore);

                // out.println("Uploaded Filename: " + fieldName + "<br>");
            } else {
                //out.println("It's not formfield");
                //out.println(fi.getString());

            }

        }

        if (aStudentInformation.startTrainingRequest(person.getSsn(), CVPath, ATPath)) {
            message.setMessage("status", 1);
        } else {
            message.setMessage("status", 0);
        }
        aSession.setAttribute("message", message);
        response.sendRedirect(request.getContextPath() + "/tirocinio/studente/tprichiestatirocinio.jsp");
        //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tirocinio/studente/tprichiestatirocinio.jsp");
        //dispatcher.forward(request,response);
    } catch (Exception ex) {
        Logger.getLogger(studentUploadFiles.class.getName()).log(Level.SEVERE, null, ex);
        message.setMessage("status", -1);
        aSession.setAttribute("message", message);
    } finally {
        out.close();
    }
}

From source file:gr.forth.ics.isl.x3mlEditor.upload.UploadReceiver.java

/**
 *
 * @param req//  w ww.  j  a v a  2s .c om
 * @param resp
 * @throws IOException
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    req.setCharacterEncoding("UTF-8");

    String targetAnalyzer = req.getParameter("targetAnalyzer");
    if (targetAnalyzer == null) {
        targetAnalyzer = targetPathSuggesterAlgorithm;
    }

    String xpath = req.getParameter("path");
    String id = req.getParameter("id");
    String filePath = "";
    RequestParser requestParser = null;
    String filename = "";
    String msg = null;

    try {
        if (ServletFileUpload.isMultipartContent(req)) {
            requestParser = RequestParser.getInstance(req,
                    new MultipartUploadParser(req, TEMP_DIR, getServletContext()));
            filename = doWriteTempFileForPostRequest(requestParser);
        } else {
            requestParser = RequestParser.getInstance(req, null);
            filename = requestParser.getFilename();
        }
    } catch (Exception e) {
        System.out.println("Problem handling upload request");
        e.printStackTrace();
        filename = requestParser.getFilename();
        msg = e.getMessage();
    }

    DBFile uploadsDBFile = new DBFile(super.DBURI, super.adminCollection, "Uploads.xml", super.DBuser,
            super.DBpassword);

    String use = "";
    if (xpath != null) {
        if (filename.endsWith("rdf") || filename.endsWith("rdfs")) {
            if (xpath.endsWith("/@rdf_link")) {
                use = "rdf_link";
            } else {
                use = "schema_file";
            }
        } else if (filename.endsWith("xml")) {
            if (xpath.endsWith("/@generator_link")) {
                use = "generator_link";
            } else {
                use = "xml_link";
            }
        }
    }
    String mime = new Utils().findMime(uploadsDBFile, filename, use);

    filename = URLEncoder.encode(filename, "UTF-8");

    TEMP_DIR = new File(uploadsFolder + "uploadsTemp");

    if (!TEMP_DIR.exists()) {
        TEMP_DIR.mkdirs();
    }

    UPLOAD_DIR = new File(uploadsFolder + mime + System.getProperty("file.separator") + filePath);

    if (!UPLOAD_DIR.exists()) {
        UPLOAD_DIR.mkdirs();
    }

    String contentLengthHeader = req.getHeader(CONTENT_LENGTH);
    Long expectedFileSize = StringUtils.isBlank(contentLengthHeader) ? null
            : Long.parseLong(contentLengthHeader);

    resp.setContentType(CONTENT_TYPE);
    resp.setStatus(RESPONSE_CODE);

    if (!ServletFileUpload.isMultipartContent(req)) {
        writeToTempFile(req.getInputStream(), new File(UPLOAD_DIR, filename), expectedFileSize);
    }

    Tidy tidy = new Tidy(DBURI, rootCollection, x3mlCollection, DBuser, DBpassword, uploadsFolder);
    String duplicate = tidy.getDuplicate(UPLOAD_DIR + System.getProperty("file.separator") + filename,
            UPLOAD_DIR.getAbsolutePath());
    boolean duplicateFound = false;

    if (duplicate != null) {
        new File(UPLOAD_DIR, filename).delete(); //Delete uploaded file!
        filename = duplicate;
        duplicateFound = true;
    }

    String xmlId = "Mapping" + id + ".xml";
    DBCollection dbc = new DBCollection(super.DBURI, applicationCollection + "/Mapping", super.DBuser,
            super.DBpassword);
    String collectionPath = getPathforFile(dbc, xmlId, id);
    DBFile mappingFile = new DBFile(DBURI, collectionPath, xmlId, DBuser, DBpassword);
    boolean isAttribute = false;
    String attributeName = "";
    if (pathIsAttribute(xpath)) { //Generic for attributes
        attributeName = xpath.substring(xpath.lastIndexOf("/") + 2);
        xpath = xpath.substring(0, xpath.lastIndexOf("/"));
        isAttribute = true;
    }
    if (isAttribute) {

        mappingFile.xAddAttribute(xpath, attributeName, filename);
        if (xpath.endsWith("/target_schema") && attributeName.equals("schema_file")
                && (filename.endsWith("rdfs") || filename.endsWith("rdf") || filename.endsWith("owl")
                        || filename.endsWith("ttl") || filename.endsWith("xml") || filename.endsWith("xsd"))) {

            //                if (!(filename.endsWith("ttl") || filename.endsWith("owl"))) {//Skip exist for owl or ttl
            if (!duplicateFound) {
                //Uploading target schema files to eXist!
                try {
                    dbc = new DBCollection(super.DBURI, x3mlCollection, super.DBuser, super.DBpassword);
                    DBFile dbf = dbc.createFile(filename, "XMLDBFile");
                    String content = readFile(new File(UPLOAD_DIR, filename), "UTF-8");
                    dbf.setXMLAsString(content);
                    dbf.store();
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                    msg = "File was uploaded but eXist queries target analyzer failed. Try using another target analyzer or upload a different file. Failure message: "
                            + ex.getMessage().replace("\n", "").replace("\r", "").replace("\"", "'");
                    ;
                }
            }
            //                }

            try {
                OntologyReasoner ont = getOntModel(mappingFile, id);

                HttpSession session = sessionCheck(req, resp);
                if (session == null) {
                    session = req.getSession();
                }
                session.setAttribute("modelInstance_" + id, ont);
                msg = null;
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
                msg = "File was uploaded but Jena reasoner target analyzer failed. Try using another target analyzer or upload a different file. Failure message: "
                        + ex.getMessage().replace("\n", "").replace("\r", "").replace("\"", "'");
                ;
            }
            //                }

        } else if (xpath.endsWith("/generator_policy_info") && (filename.endsWith("xml"))) {

            if (!duplicateFound) {
                //Uploading generator policy files to eXist!
                dbc = new DBCollection(super.DBURI, x3mlCollection, super.DBuser, super.DBpassword);
                DBFile dbf = dbc.createFile(filename, "XMLDBFile");
                String content = readFile(new File(UPLOAD_DIR, filename), "UTF-8");
                dbf.setXMLAsString(content);
                dbf.store();
            }
        }

    } else {
        mappingFile.xUpdate(xpath, filename);
    }

    writeResponse(filename, resp.getWriter(), msg, mime);

}

From source file:fr.insalyon.creatis.vip.datamanager.server.rpc.FileUploadServiceImpl.java

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

    User user = (User) request.getSession().getAttribute(CoreConstants.SESSION_USER);
    if (user != null && ServletFileUpload.isMultipartContent(request)) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {/*from   ww  w .  jav  a  2s  . c o m*/
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            String fileName = null;
            FileItem fileItem = null;
            String path = null;
            String target = "uploadComplete";
            String operationID = "no-id";

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.getFieldName().equals("path")) {
                    path = item.getString();
                } else if (item.getFieldName().equals("file")) {
                    fileName = item.getName();
                    fileItem = item;
                } else if (item.getFieldName().equals("target")) {
                    target = item.getString();
                }
            }
            if (fileName != null && !fileName.equals("")) {

                boolean local = path.equals("local") ? true : false;
                String rootDirectory = DataManagerUtil.getUploadRootDirectory(local);
                fileName = new File(fileName).getName().trim().replaceAll(" ", "_");
                fileName = Normalizer.normalize(fileName, Normalizer.Form.NFD)
                        .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
                File uploadedFile = new File(rootDirectory + fileName);

                try {
                    fileItem.write(uploadedFile);
                    response.getWriter().write(fileName);

                    if (!local) {
                        // GRIDA Pool Client
                        logger.info("(" + user.getEmail() + ") Uploading '" + uploadedFile.getAbsolutePath()
                                + "' to '" + path + "'.");
                        GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient();
                        operationID = client.uploadFile(uploadedFile.getAbsolutePath(),
                                DataManagerUtil.parseBaseDir(user, path), user.getEmail());

                    } else {
                        operationID = fileName;
                        logger.info(
                                "(" + user.getEmail() + ") Uploaded '" + uploadedFile.getAbsolutePath() + "'.");
                    }
                } catch (Exception ex) {
                    logger.error(ex);
                }
            }

            response.setContentType("text/html");
            response.setHeader("Pragma", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<body>");
            out.println("<script type=\"text/javascript\">");
            out.println("if (parent." + target + ") parent." + target + "('" + operationID + "');");
            out.println("</script>");
            out.println("</body>");
            out.println("</html>");
            out.flush();

        } catch (FileUploadException ex) {
            logger.error(ex);
        }
    }
}

From source file:Controller.ProsesRegis.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {//  w w w .  ja  v a 2  s . c  o  m
        /* TODO output your page here. You may use following sample code. */
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                if (fileItem.isFormField()) {
                    processFormField(fileItem);
                } else {
                    flItem = fileItem;
                }
            }
            try {
                Photo = flItem.getName();
                File savedFile = new File(
                        "D:\\Latihan Java\\web\\AplikasiPMB\\web\\backend\\images_student\\" + Photo);
                flItem.write(savedFile);
            } catch (Exception e) {
                out.println(e);
                System.out.println(e.getMessage());
            }

            KoneksiDatabase obj_con = new KoneksiDatabase();

            Code b = new Code();
            b.setIdStudent(IdStudent);
            b.setFullname(Fullname);
            b.setIdMajor(IdMajor);
            b.setGender(Gender);
            b.setBirth(Birth);
            b.setSchool(School);
            b.setmajor(Major);
            b.setAddress(Address);
            b.setPhone(Phone);
            b.setEmail(Email);
            b.setGraduation(Grayear);
            b.setPhoto(Photo);

            int i = b.Registration();
            int g = b.doUpdate(IdMajor);
            if (i > 0) {
                RequestDispatcher rd = request.getRequestDispatcher("frontend/index.jsp");
                request.setAttribute("return", "Regristration Successfully!");
                rd.forward(request, response);
                //response.sendRedirect("frontend/index.jsp");
            } else {
                RequestDispatcher rd = request.getRequestDispatcher("frontend/index.jsp");
                request.setAttribute("return", "Registration Failed!");
                rd.forward(request, response);
            }
        }
    } catch (Exception ex) {
        out.println(ex.getCause());
        System.out.println(ex.getMessage());
    }
    /* TODO output your page here. You may use following sample code. */

}

From source file:com.utilities.FileManager.java

public FileManager(ServletContext servletContext, HttpServletRequest request) {
    // get document root like in php
    String contextPath = request.getContextPath();
    String documentRoot = servletContext.getRealPath("/").replaceAll("\\\\", "/");
    System.out.println("CP: " + contextPath + " DR: " + documentRoot);
    //documentRoot = documentRoot.substring(0, documentRoot.indexOf(contextPath));

    this.referer = request.getHeader("referer");
    System.out.println("Referer: " + this.referer);
    this.fileManagerRoot = documentRoot; //+ referer.substring(referer.indexOf(contextPath), referer.indexOf("fileManager.jsp"));

    // get uploaded file list
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    if (ServletFileUpload.isMultipartContent(request))
        try {//from   w  w  w . j  a  va  2 s.  c o  m
            files = upload.parseRequest(request);
        } catch (Exception e) { // no error handling}
        }

    this.properties.put("Date Created", null);
    this.properties.put("Date Modified", null);
    this.properties.put("Height", null);
    this.properties.put("Width", null);
    this.properties.put("Size", null);

    // load config file
    loadConfig();

    if (config.getProperty("doc_root") != null)
        this.documentRoot = config.getProperty("doc_root");
    else
        this.documentRoot = documentRoot;

    dateFormat = new SimpleDateFormat(config.getProperty("date"));

    this.setParams();

    loadLanguageFile();
}