Example usage for org.apache.commons.fileupload FileItem getContentType

List of usage examples for org.apache.commons.fileupload FileItem getContentType

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getContentType.

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:com.dien.manager.servlet.UploadShpServlet.java

/**
 * Override executeAction to save the received files in a custom place and delete this items from session.
 *///from   ww w .  ja  v  a2s . c  om
@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    String response = "";
    int cont = 0;
    HttpSession session = request.getSession();
    User users = (User) session.getAttribute("user");
    if (users != null && users.isDataAuth()) {

        for (FileItem item : sessionFiles) {
            if (false == item.isFormField()) {
                cont++;
                try {
                    // 1. ?
                    File file = File.createTempFile(item.getFieldName(), ".zip");
                    item.write(file);
                    FileInputStream fis = new FileInputStream(file);
                    if (fis.available() > 0) {
                        System.out.println("File has " + fis.available() + " bytes");
                        // 2.zip
                        CopyFile copyFile = new CopyFile();
                        String tmpFolder = Config.getOutPath() + File.separator + item.getFieldName();
                        copyFile.delFolder(tmpFolder);
                        copyFile.newFolder(tmpFolder);
                        ZipUtil.unZip(file.getAbsolutePath(), tmpFolder + File.separator, true);
                        // 3.???shp
                        ArrayList<String> slist = new ArrayList<String>();
                        getAllFile(new File(tmpFolder), slist);
                        if (slist.size() > 0) {
                            ArrayList<String> msglist = new ArrayList<String>();
                            if (checkShpFileComplete(slist.get(0), msglist)) {
                                // 4. shp
                                // SDEWrapper sde = new SDEWrapper(Config.getProperties());
                                File shpFile = new File(slist.get(0));
                                String path = shpFile.getPath();
                                String layerName = shpFile.getName();
                                layerName = layerName.substring(0, layerName.indexOf("."));
                                // ???
                                // ??
                                layerName = basis.generatorTableName(layerName);
                                session.setAttribute(layerName, path);
                                // sde.shpToSde(path, layerName);
                                // 5. ?
                                logger.info("--" + file.getAbsolutePath() + "--isexist: " + file.exists());

                                // / Save a list with the received files
                                receivedFiles.put(item.getFieldName(), file);
                                receivedContentTypes.put(item.getFieldName(), item.getContentType());

                                // / Compose a xml message with the full file information
                                response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont
                                        + "-field>\n";
                                response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont
                                        + "-name>\n";
                                response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont
                                        + "-size>\n";
                                response += "<file-" + cont + "-type>" + item.getContentType() + "</file-"
                                        + cont + "type>\n";
                                response += "<file-" + cont + "-layerid>" + layerName + "</file-" + cont
                                        + "layerid>\n";
                            } else {
                                response += "<file-" + cont + "-error>" + Util.listToWhere(msglist, ",")
                                        + "</file-" + cont + "error>\n";
                            }
                        } else {
                            response += "<file-" + cont + "-error>zipshp</file-"
                                    + cont + "error>\n";
                        }
                    } else {
                        response += "<file-" + cont + "-error>?</file-" + cont
                                + "error>\n";
                    }
                } catch (IOException e) {
                    response += "<file-" + cont
                            + "-error>shpshp??????</file-"
                            + cont + "error>\n";

                } catch (InterruptedException e) {
                    response += "<file-" + cont + "-error>??</file-" + cont
                            + "error>\n";

                } catch (Exception e) {
                    response += "<file-" + cont
                            + "-error>???</file-" + cont
                            + "error>\n";

                }
            }
        }
    } else {
        response += "<file-" + cont + "-error>???</file-" + cont + "error>\n";
    }
    // / Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    // / Send information of the received files to the client.
    return "<response>\n" + response + "</response>\n";
}

From source file:com.cognitivabrasil.repositorio.web.FileController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody//from   w w w . j  a va  2 s .com
public String upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException {
    if (file == null) {
        file = new Files();
        file.setSizeInBytes(0L);
    }

    Integer docId = null;
    String docPath = null;
    String responseString = RESP_SUCCESS;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        try {
            ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = x.parseRequest(request);

            for (FileItem item : items) {
                InputStream input = item.getInputStream();

                // Handle a form field.
                if (item.isFormField()) {
                    String attribute = item.getFieldName();
                    String value = Streams.asString(input);

                    switch (attribute) {
                    case "chunks":
                        this.chunks = Integer.parseInt(value);
                        break;
                    case "chunk":
                        this.chunk = Integer.parseInt(value);
                        break;
                    case "filename":
                        file.setName(value);
                        break;
                    case "docId":
                        if (value.isEmpty()) {
                            throw new org.apache.commons.fileupload.FileUploadException(
                                    "No foi informado o id do documento.");
                        }
                        docId = Integer.parseInt(value);
                        docPath = Config.FILE_PATH + "/" + docId;
                        File documentPath = new File(docPath);
                        // cria o diretorio
                        documentPath.mkdirs();

                        break;
                    default:
                        break;
                    }

                } // Handle a multi-part MIME encoded file.
                else {
                    try {

                        File uploadFile = new File(docPath, item.getName());
                        BufferedOutputStream bufferedOutput;
                        bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true));

                        byte[] data = item.get();
                        bufferedOutput.write(data);
                        bufferedOutput.close();
                    } catch (Exception e) {
                        LOG.error("Erro ao salvar o arquivo.", e);
                        file = null;
                        throw e;
                    } finally {
                        if (input != null) {
                            try {
                                input.close();
                            } catch (IOException e) {
                                LOG.error("Erro ao fechar o ImputStream", e);
                            }
                        }

                        file.setName(item.getName());
                        file.setContentType(item.getContentType());
                        file.setPartialSize(item.getSize());
                    }
                }
            }

            if ((this.chunk == this.chunks - 1) || this.chunks == 0) {
                file.setLocation(docPath + "/" + file.getName());
                if (docId != null) {
                    file.setDocument(documentsService.get(docId));
                }
                fileService.save(file);
                file = null;
            }
        } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) {
            responseString = RESP_ERROR;
            LOG.error("Erro ao salvar o arquivo", e);
            file = null;
            throw e;
        }
    } // Not a multi-part MIME request.
    else {
        responseString = RESP_ERROR;
    }

    response.setContentType("application/json");
    byte[] responseBytes = responseString.getBytes();
    response.setContentLength(responseBytes.length);
    ServletOutputStream output = response.getOutputStream();
    output.write(responseBytes);
    output.flush();
    return responseString;
}

From source file:com.dien.upload.server.UploadShpServlet.java

/**
 * Override executeAction to save the received files in a custom place and delete this items from session.
 *///from  w  ww  .  j av a  2 s . c  om
@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    JSONObject obj = new JSONObject();
    HttpSession session = request.getSession();
    User users = (User) session.getAttribute("user");
    if (users != null && users.isDataAuth()) {

        for (FileItem item : sessionFiles) {
            if (false == item.isFormField()) {

                try {
                    // 1. ?
                    File file = File.createTempFile(item.getFieldName(), ".zip");
                    item.write(file);
                    FileInputStream fis = new FileInputStream(file);
                    if (fis.available() > 0) {
                        System.out.println("File has " + fis.available() + " bytes");
                        // 2.zip
                        CopyFile copyFile = new CopyFile();

                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        //
                        String tmpFolder = Config.getOutPath() + File.separator + item.getFieldName() + "_"
                                + df.format(new Date()) + "_" + new Random().nextInt(1000);
                        copyFile.delFolder(tmpFolder);
                        copyFile.newFolder(tmpFolder);
                        ZipUtil.unZip(file.getAbsolutePath(), tmpFolder + File.separator, true);
                        // 3.???shp
                        ArrayList<String> slist = new ArrayList<String>();
                        getAllFile(new File(tmpFolder), slist);
                        if (slist.size() > 0) {
                            ArrayList<String> msglist = new ArrayList<String>();
                            if (checkShpFileComplete(slist.get(0), msglist)) {
                                // 4. shp
                                // SDEWrapper sde = new SDEWrapper(Config.getProperties());
                                File shpFile = new File(slist.get(0));
                                String path = shpFile.getPath();
                                String layerName = shpFile.getName();
                                layerName = layerName.substring(0, layerName.indexOf("."));
                                // ???
                                // ??
                                layerName = basis.generatorTableName(layerName);
                                session.setAttribute(layerName, path);
                                // sde.shpToSde(path, layerName);
                                // 5. ?
                                // logger.info("--" + file.getAbsolutePath() + "--isexist: "+ file.exists());

                                // / Save a list with the received files
                                receivedFiles.put(item.getFieldName(), file);
                                receivedContentTypes.put(item.getFieldName(), item.getContentType());

                                /// Compose a xml message with the full file information
                                obj.put("fieldname", item.getFieldName());
                                obj.put("name", item.getName());
                                obj.put("size", item.getSize());
                                obj.put("type", item.getContentType());
                                obj.put("layerName", layerName);
                                obj.put("ret", true);
                                obj.put("msg", "??");

                            } else {
                                obj.put("ret", false);
                                obj.put("msg", Util.listToWhere(msglist, ","));
                            }
                        } else {
                            obj.put("ret", false);
                            obj.put("msg", "zipshp");
                        }
                    } else {
                        obj.put("ret", false);
                        obj.put("msg", "?");
                    }
                } catch (IOException e) {
                    obj.put("ret", false);
                    obj.put("msg", "shpshp?????");
                } catch (InterruptedException e) {
                    obj.put("ret", false);
                    obj.put("msg", "??");
                } catch (Exception e) {
                    obj.put("ret", false);
                    obj.put("msg", "??");
                }
            }
        }
    } else {
        obj.put("msg", "??");
    }
    removeSessionFileItems(request);
    return obj.toString();
}

From source file:com.edgenius.wiki.webapp.servlet.UploadServlet.java

@SuppressWarnings("unchecked")
protected void doService(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if ("GET".equalsIgnoreCase(request.getMethod())) {
        //just render blank page for upload
        String pageUuid = request.getParameter("puuid");
        String spaceUname = request.getParameter("uname");
        String draft = request.getParameter("draft");

        request.setAttribute("pageUuid", pageUuid);
        request.setAttribute("spaceUname", spaceUname);
        request.setAttribute("draft", NumberUtils.toInt(draft, PageType.NONE_DRAFT.value()));

        request.getRequestDispatcher("/WEB-INF/pages/upload.jsp").forward(request, response);

        return;// w w w  .ja v  a  2  s  . co  m
    }

    //post - upload

    //      if(WikiUtil.getUser().isAnonymous()){
    //      //anonymous can not allow to upload any files

    PageService pageService = getPageService();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

    List<FileNode> files = new ArrayList<FileNode>();
    String pageUuid = null, spaceUname = null;
    try {
        int status = PageType.NONE_DRAFT.value();
        // index->filename
        Map<String, FileItem> fileMap = new HashMap<String, FileItem>();
        Map<String, String> descMap = new HashMap<String, String>();
        // index->index
        Map<String, String> indexMap = new HashMap<String, String>();

        //offline submission, filename put into hidden variable rather than <input type="file> tag
        Map<String, String> filenameMap = new HashMap<String, String>();
        //TODO: offline submission, version also upload together with file, this give a change to do failure tolerance check:
        //if version is same with online save, then it is OK, if greater, means it maybe duplicated upload, if less, unpexected case
        Map<String, String> versionMap = new HashMap<String, String>();

        Map<String, Boolean> bulkMap = new HashMap<String, Boolean>();

        Map<String, Boolean> sharedMap = new HashMap<String, Boolean>();
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            String name = item.getFieldName();
            if (StringUtils.equals(name, "spaceUname")) {
                spaceUname = item.getString(Constants.UTF8);
            } else if (StringUtils.equals(name, "pageUuid")) {
                pageUuid = item.getString();
            } else if (name.startsWith("draft")) {
                // check this upload is from "click save button" or "auto upload in draft status"
                status = Integer.parseInt(item.getString());
            } else if (name.startsWith("file")) {
                fileMap.put(name.substring(4), item);
                indexMap.put(name.substring(4), name.substring(4));
            } else if (name.startsWith("desc")) {
                descMap.put(name.substring(4), item.getString(Constants.UTF8));
            } else if (name.startsWith("shar")) {
                sharedMap.put(name.substring(4), Boolean.parseBoolean(item.getString()));
            } else if (name.startsWith("name")) {
                filenameMap.put(name.substring(4), item.getString());
            } else if (name.startsWith("vers")) {
                versionMap.put(name.substring(4), item.getString());
            } else if (name.startsWith("bulk")) {
                bulkMap.put(name.substring(4), BooleanUtils.toBoolean(item.getString()));
            }
        }
        if (StringUtils.isBlank(pageUuid)) {
            log.error("Attachment can not be load because of page does not save successfully.");
            throw new PageException("Attachment can not be load because of page does not save successfully.");
        }

        List<FileNode> bulkFiles = new ArrayList<FileNode>();
        String username = request.getRemoteUser();
        // put file/desc pair into final Map
        for (String id : fileMap.keySet()) {
            FileItem item = fileMap.get(id);
            if (item == null || item.getInputStream() == null || item.getSize() <= 0) {
                log.warn("Empty upload item:" + (item != null ? item.getName() : ""));
                continue;
            }
            FileNode node = new FileNode();
            node.setComment(descMap.get(id));
            node.setShared(sharedMap.get(id) == null ? false : sharedMap.get(id));
            node.setFile(item.getInputStream());
            String filename = item.getName();
            if (StringUtils.isBlank(filename)) {
                //this could be offline submission, get name from map
                filename = filenameMap.get(id);
            }
            node.setFilename(FileUtil.getFileName(filename));
            node.setContentType(item.getContentType());
            node.setIndex(indexMap.get(id));
            node.setType(RepositoryService.TYPE_ATTACHMENT);
            node.setIdentifier(pageUuid);
            node.setCreateor(username);
            node.setStatus(status);
            node.setSize(item.getSize());
            node.setBulkZip(bulkMap.get(id) == null ? false : bulkMap.get(id));

            files.add(node);

            if (node.isBulkZip())
                bulkFiles.add(node);
        }
        if (spaceUname != null && pageUuid != null && files.size() > 0) {
            files = pageService.uploadAttachments(spaceUname, pageUuid, files, false);

            //only save non-draft uploaded attachment
            if (status == 0) {
                try {
                    getActivityLog().logAttachmentUploaded(spaceUname,
                            pageService.getCurrentPageByUuid(pageUuid).getTitle(), WikiUtil.getUser(), files);
                } catch (Exception e) {
                    log.warn("Activity log save error for attachment upload", e);
                }
            }
            //as bulk files won't in return list in PageService.uploadAttachments(), here need 
            //append to all return list, but only for client side "uploading panel" clean purpose
            files.addAll(bulkFiles);
            //TODO: if version come in together, then do check
            //            if(versionMap.size() > 0){
            //               for (FileNode node: files) {
            //                  
            //               }
            //            }
        }

    } catch (RepositoryQuotaException e) {
        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.quota.exhaust"));
        files = Arrays.asList(att);
    } catch (AuthenticationException e) {
        String redir = ((RedirectResponseWrapper) response).getRedirect();
        if (redir == null)
            redir = WikiConstants.URL_LOGIN;
        log.info("Send Authentication redirect URL " + redir);

        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.authentication.required"));
        files = Arrays.asList(att);

    } catch (AccessDeniedException e) {
        String redir = ((RedirectResponseWrapper) response).getRedirect();
        if (redir == null)
            redir = WikiConstants.URL_ACCESS_DENIED;
        log.info("Send AccessDenied redirect URL " + redir);

        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.access.denied"));
        files = Arrays.asList(att);

    } catch (Exception e) {
        // FileUploadException,RepositoryException
        log.error("File upload failed ", e);
        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.upload"));
        files = Arrays.asList(att);
    }

    try {
        String json = FileNode.toAttachmentsJson(files, spaceUname, WikiUtil.getUser(), getMessageService(),
                getUserReadingService());

        //TODO: does not compress request in Gzip, refer to 
        //http://www.google.com/codesearch?hl=en&q=+RemoteServiceServlet+show:PAbNFg2Qpdo:akEoB_bGF1c:4aNSrXYgYQ4&sa=N&cd=1&ct=rc&cs_p=https://ssl.shinobun.org/svn/repos/trunk&cs_f=proprietary/gwt/gwt-user/src/main/java/com/google/gwt/user/server/rpc/RemoteServiceServlet.java#first
        byte[] reply = json.getBytes(Constants.UTF8);
        response.setContentLength(reply.length);
        response.setContentType("text/plain; charset=utf-8");
        response.getOutputStream().write(reply);
    } catch (IOException e) {
        log.error(e.toString(), e);
    }
}

From source file:dk.clarin.tools.create.java

public String getParmsAndFiles(List<FileItem> items, HttpServletResponse response, PrintWriter out)
        throws ServletException {
    if (!BracMat.loaded()) {
        response.setStatus(500);//  w  ww . j a v  a2 s. co  m
        throw new ServletException("Bracmat is not loaded. Reason:" + BracMat.reason());
    }

    String arg = "(method.POST) (DATE." + workflow.quote(date) + ")"; // bj 20120801 "(action.POST)";

    try {
        /*
        * Parse the request
        */
        Iterator<FileItem> itr = items.iterator();
        while (itr.hasNext()) {
            logger.debug("in loop");
            FileItem item = itr.next();
            /*
            * Handle Form Fields.
            */
            if (item.isFormField()) {
                logger.debug("Field Name = " + item.getFieldName() + ", String = " + item.getString());
                if (item.getFieldName().equals("text")) {
                    String LocalFileName = BracMat
                            .Eval("storeUpload$(" + workflow.quote("text") + "." + workflow.quote(date) + ")");
                    int textLength = item.getString().length();

                    File file = new File(destinationDir, LocalFileName);
                    item.write(file);
                    arg = arg + " (FieldName," + workflow.quote("text") + ".Name," + workflow.quote("text")
                            + ".ContentType," + workflow.quote("text/plain") + ".Size,"
                            + Long.toString(textLength) + ".DestinationDir,"
                            + workflow.quote(
                                    ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*//*DESTINATION_DIR_PATH*/)
                            + ".LocalFileName," + workflow.quote(LocalFileName) + ")";
                } else
                    arg = arg + " (" + workflow.quote(item.getFieldName()) + "."
                            + workflow.quote(item.getString()) + ")";
            } else if (item.getName() != "") {
                //Handle Uploaded files.
                String LocalFileName = BracMat.Eval(
                        "storeUpload$(" + workflow.quote(item.getName()) + "." + workflow.quote(date) + ")");
                /*
                * Write file to the ultimate location.
                */
                File file = new File(destinationDir, LocalFileName);
                item.write(file);

                String ContentType = item.getContentType();
                logger.debug("hasNoPDFfonts ?");
                logger.debug("ContentType :" + ContentType);
                boolean hasNoPDFfonts = false;
                if (ContentType.equals("application/pdf") || ContentType.equals("application/x-download")
                        || ContentType.equals("application/octet-stream")) {
                    logger.debug("calling PDFhasNoFonts");
                    hasNoPDFfonts = PDFhasNoFonts(file);
                    logger.debug("hasNoPDFfonts " + (hasNoPDFfonts ? "true" : "false"));
                }
                arg = arg + " (FieldName," + workflow.quote(item.getFieldName()) + ".Name,"
                        + workflow.quote(item.getName()) + ".ContentType,"
                        + workflow.quote(item.getContentType()) + (hasNoPDFfonts ? " true" : "") + ".Size,"
                        + Long.toString(item.getSize()) + ".DestinationDir,"
                        + workflow.quote(
                                ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*//*DESTINATION_DIR_PATH*/)
                        + ".LocalFileName," + workflow.quote(LocalFileName) + ")";
            }
        }
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
        out.close();
    }
    logger.debug("arg " + arg);
    return arg;
}

From source file:it.infn.ct.ParallelSemanticSearch_portlet.java

public void getInputForm(ActionRequest request, App_Input appInput) {
    if (PortletFileUpload.isMultipartContent(request)) {
        try {/* w w  w .  j a va2  s  .  co  m*/
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {

                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName                                                   
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    } // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        appInput.search_word = (String) request.getParameter("search_word");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
        appInput.nameSubject = (String) request.getParameter("nameSubject");

        appInput.idResouce = (String) request.getParameter("idResource");
        appInput.selected_language = (String) request.getParameter("selLanguage");
        appInput.numberPage = (String) request.getParameter("numberOfPage");
        appInput.numberPageOpenAgris = (String) request.getParameter("numberOfPageOpenAgris");
        appInput.numRecordsForPage = (String) request.getParameter("numberOfRecords");
        appInput.moreResourceCHAIN = (String) request.getParameter("moreResourceCHAIN");
        appInput.moreResourceOpenAgris = (String) request.getParameter("moreResourceOpenAgris");
        appInput.idResourceOpenAgris = (String) request.getParameter("idResourceOpenAgris");
        appInput.moreInfoOpenAgris = (String) request.getParameter("moreInfoOpenAgris");
        appInput.moreInfo = (String) request.getParameter("moreInfo");
        appInput.numberPageCulturaItalia = (String) request.getParameter("numberOfPageCulturaItalia");
        appInput.moreResourceCulturaItalia = (String) request.getParameter("moreResourceCulturaItalia");
        appInput.moreInfoCulturaItalia = (String) request.getParameter("moreInfoCulturaItalia");
        appInput.numResource = (String) request.getParameter("numResource");
        appInput.numResourceFromDetails = (String) request.getParameter("numResourceFromDetails");
        appInput.numResourceOpenAgris = (String) request.getParameter("numResourceOpenAgris");
        appInput.numResourceOpenAgrisFromDetails = (String) request
                .getParameter("numResourceOpenAgrisFromDetails");
        appInput.numResourceCulturaItalia = (String) request.getParameter("numResourceCulturaItalia");
        appInput.numResourceCulturaItaliaFromDetails = (String) request
                .getParameter("numResourceCulturaItaliaFromDetails");
        appInput.idResourceCulturaItalia = (String) request.getParameter("idResourceCulturaItalia");

        appInput.numberPageIsidore = (String) request.getParameter("numberOfPageIsidore");
        appInput.moreResourceIsidore = (String) request.getParameter("moreResourceIsidore");
        appInput.idResourceIsidore = (String) request.getParameter("idResourceIsidore");
        appInput.numResourceIsidore = (String) request.getParameter("numResourceIsidore");
        appInput.numResourceIsidoreFromDetails = (String) request.getParameter("numResourceIsidoreFromDetails");
        appInput.numberPageIsidore = (String) request.getParameter("numberOfPageIsidore");
        appInput.moreInfoIsidore = (String) request.getParameter("moreInfoIsidore");

        appInput.idResourceEuropeana = (String) request.getParameter("idResourceEuropeana");
        appInput.moreResourceEuropeana = (String) request.getParameter("moreResourceEuropeana");
        appInput.numberPageEuropeana = (String) request.getParameter("numberOfPageEuropeana");
        appInput.numResourceEuropeana = (String) request.getParameter("numResourceEuropeana");
        appInput.numResourceEuropeanaFromDetails = (String) request
                .getParameter("numResourceEuropeanaFromDetails");
        appInput.numberPageEuropeana = (String) request.getParameter("numberOfPageEuropeana");
        appInput.moreInfoEuropeana = (String) request.getParameter("moreInfoEuropeana");

        appInput.idResourcePubmed = (String) request.getParameter("idResourcePubmed");
        appInput.moreResourcePubmed = (String) request.getParameter("moreResourcePubmed");
        appInput.numberPagePubmed = (String) request.getParameter("numberOfPagePubmed");
        appInput.numResourcePubmed = (String) request.getParameter("numResourcePubmed");
        appInput.numResourcePubmedFromDetails = (String) request.getParameter("numResourcePubmedFromDetails");
        appInput.moreInfoPubmed = (String) request.getParameter("moreInfoPubmed");

        appInput.idResourceEngage = (String) request.getParameter("idResourceEngage");
        appInput.moreResourceEngage = (String) request.getParameter("moreResourceEngage");
        appInput.numberPageEngage = (String) request.getParameter("numberOfPageEngage");
        appInput.numResourceEngage = (String) request.getParameter("numResourceEngage");
        appInput.numResourceEngageFromDetails = (String) request.getParameter("numResourceEngageFromDetails");
        appInput.moreInfoEngage = (String) request.getParameter("moreInfoEngage");
        appInput.title_GS = (String) request.getParameter("title_GS");

    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "Search Word: '"
            + appInput.search_word + "'" + LS + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS
            + "subject: '" + appInput.nameSubject + "'" + LS + "idResource: '" + appInput.idResouce + "'" + LS
            + "language selected: '" + appInput.selected_language + "'" + LS + "number page selected: '"
            + appInput.numberPage + "'" + LS + "number record for page: '" + appInput.numRecordsForPage + "'"
            + LS + "number page selected OpenAgris: '" + appInput.numberPageOpenAgris + "'" + LS
            + "moreResourceCHAIN: '" + appInput.moreResourceCHAIN + "'" + LS + "moreInfo: '" + appInput.moreInfo
            + "'" + LS + "moreResourceOpenAgris: '" + appInput.moreResourceOpenAgris + "'" + LS
            + "idResourceOpenAgris: '" + appInput.idResourceOpenAgris + "'" + LS + "moreInfoOpenAgris: '"
            + appInput.moreInfoOpenAgris + "'" + LS + "number page selected CulturaItalia: '"
            + appInput.numberPageCulturaItalia + "'" + LS + "moreResourceCulturaItalia: '"
            + appInput.moreResourceCulturaItalia + "'" + LS + "moreInfoCulturaItalia: '"
            + appInput.moreInfoCulturaItalia + "'" + LS + "NumResource: '" + appInput.numResource + "'" + LS
            + "NumResourceFromDetails: '" + appInput.numResourceFromDetails + "'" + LS
            + "NumResourceOpenAgris: '" + appInput.numResourceOpenAgris + "'" + LS
            + "NumResourceOpenAgrisFromDetails: '" + appInput.numResourceOpenAgrisFromDetails + "'" + LS
            + "NumResourceCulturaItalia: '" + appInput.numResourceCulturaItalia + "'" + LS
            + "NumResourceCulturaItaliaFromDetails: '" + appInput.numResourceCulturaItaliaFromDetails + "'" + LS
            + "idResourceCulturaItalia: '" + appInput.idResourceCulturaItalia + "'" + LS
            + "moreResourceEuropeana: '" + appInput.moreResourceEuropeana + "'" + LS);
}

From source file:importer.handler.post.ImporterPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request//from  w w  w  .j  a  va 2 s . c  om
 */
void parseImportParams(HttpServletRequest request) throws AeseException {
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.DOCID)) {
                        if (contents.startsWith("/")) {
                            contents = contents.substring(1);
                            int pos = contents.indexOf("/");
                            if (pos != -1) {
                                database = contents.substring(0, pos);
                                contents = contents.substring(pos + 1);
                            }
                        }
                        docid = contents;
                    } else if (fieldName.startsWith(Params.SHORT_VERSION))
                        nameMap.put(fieldName.substring(Params.SHORT_VERSION.length()), item.getString());
                    else if (fieldName.equals(Params.LC_STYLE) || fieldName.equals(Params.STYLE)
                            || fieldName.equals(Params.CORFORM)) {
                        jsonKeys.put(fieldName.toLowerCase(), contents);
                        style = contents;
                    } else if (fieldName.equals(Params.DEMO)) {
                        if (contents != null && contents.equals("brillig"))
                            demo = false;
                        else
                            demo = true;
                    } else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.FILTER))
                        filterName = contents.toLowerCase();
                    else if (fieldName.equals(Params.SIMILARITY))
                        similarityTest = contents != null && contents.equals("1");
                    else if (fieldName.equals(Params.SPLITTER))
                        splitterName = contents;
                    else if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.TEXT))
                        textName = contents.toLowerCase();
                    else if (fieldName.equals(Params.DICT))
                        dict = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.HH_EXCEPTIONS))
                        hhExceptions = contents;
                    else
                        jsonKeys.put(fieldName, contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // assuming that the contents are text
                    //item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null && type.startsWith("image/")) {
                        InputStream is = item.getInputStream();
                        ByteHolder bh = new ByteHolder();
                        while (is.available() > 0) {
                            byte[] b = new byte[is.available()];
                            is.read(b);
                            bh.append(b);
                        }
                        ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData());
                        images.add(iFile);
                    } else {
                        byte[] rawData = item.get();
                        guessEncoding(rawData);
                        //System.out.println(encoding);
                        File f = new File(item.getName(), new String(rawData, encoding));
                        files.add(f);
                    }
                } catch (Exception e) {
                    throw new AeseException(e);
                }
            }
        }
        if (style == null)
            style = DEFAULT_STYLE;
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:calliope.handler.post.AeseImportHandler.java

/**
 * Parse the import params from the request
 * @param request the http request//w w  w .j a va 2  s  . com
 */
void parseImportParams(HttpServletRequest request) throws AeseException {
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.DOCID)) {
                        if (contents.startsWith("/")) {
                            contents = contents.substring(1);
                            int pos = contents.indexOf("/");
                            if (pos != -1) {
                                database = contents.substring(0, pos);
                                contents = contents.substring(pos + 1);
                            }
                        }
                        docID = new DocID(contents);
                    } else if (fieldName.startsWith(Params.SHORT_VERSION))
                        nameMap.put(fieldName.substring(Params.SHORT_VERSION.length()), item.getString());
                    else if (fieldName.equals(Params.LC_STYLE) || fieldName.equals(Params.STYLE)) {
                        jsonKeys.put(fieldName.toLowerCase(), contents);
                        style = contents;
                    } else if (fieldName.equals(Params.DEMO)) {
                        if (contents != null && contents.equals("brillig"))
                            demo = false;
                        else
                            demo = true;
                    } else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.FILTER))
                        filterName = contents.toLowerCase();
                    else if (fieldName.equals(Params.SIMILARITY))
                        similarityTest = contents != null && contents.equals("1");
                    else if (fieldName.equals(Params.SPLITTER))
                        splitterName = contents;
                    else if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.TEXT))
                        textName = contents.toLowerCase();
                    else if (fieldName.equals(Params.XSLT))
                        xslt = getConfig(Config.xslt, contents);
                    else if (fieldName.equals(Params.DICT))
                        dict = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.HH_EXCEPTIONS))
                        hhExceptions = contents;
                    else
                        jsonKeys.put(fieldName, contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // assuming that the contents are text
                    //item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null && type.startsWith("image/")) {
                        InputStream is = item.getInputStream();
                        ByteHolder bh = new ByteHolder();
                        while (is.available() > 0) {
                            byte[] b = new byte[is.available()];
                            is.read(b);
                            bh.append(b);
                        }
                        ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData());
                        images.add(iFile);
                    } else {
                        byte[] rawData = item.get();
                        guessEncoding(rawData);
                        //System.out.println(encoding);
                        File f = new File(item.getName(), new String(rawData, encoding));
                        files.add(f);
                    }
                } catch (Exception e) {
                    throw new AeseException(e);
                }
            }
        }
        if (style == null)
            style = DEFAULT_STYLE;
    } catch (Exception e) {
        throw new AeseException(e);
    }
    //        System.out.println("Import params received:");
    //        System.out.println("docID="+docID.get());
    //        System.out.println("style="+style);
    //        System.out.println("filterName="+filterName);
    //        System.out.println("database="+database);
    //        System.out.println("splitterName="+splitterName);
    //        System.out.println("stripperName="+stripperName);
    //        System.out.println("encoding="+encoding);
    //        System.out.println("hhExceptions="+hhExceptions);
    //        System.out.println("similarityTest="+similarityTest);
    //        System.out.println("dict="+dict);
    //        System.out.println("xslt="+xslt);
    //        System.out.println("demo="+demo);
    //        System.out.println("textName="+textName);
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.FedoraDatastreamController.java

@Override
public void doPost(HttpServletRequest rawRequest, HttpServletResponse res)
        throws ServletException, IOException {
    try {/* w w  w  .j  a  v  a  2  s.  c o  m*/
        VitroRequest req = new VitroRequest(rawRequest);
        if (req.hasFileSizeException()) {
            throw new FdcException("Size limit exceeded: " + req.getFileSizeException().getLocalizedMessage());
        }
        if (!req.isMultipart()) {
            throw new FdcException("Must POST a multipart encoded request");
        }

        //check if fedora is on line
        OntModel sessionOntModel = ModelAccess.on(getServletContext()).getOntModel();
        synchronized (FedoraDatastreamController.class) {
            if (fedoraUrl == null) {
                setup(sessionOntModel, getServletContext());
                if (fedoraUrl == null)
                    throw new FdcException("Connection to the file repository is "
                            + "not setup correctly.  Could not read fedora.properties file");
            } else {
                if (!canConnectToFedoraServer()) {
                    fedoraUrl = null;
                    throw new FdcException("Could not connect to Fedora.");
                }
            }
        }
        FedoraClient fedora;
        try {
            fedora = new FedoraClient(fedoraUrl, adminUser, adminPassword);
        } catch (MalformedURLException e) {
            throw new FdcException("Malformed URL for fedora Repository location: " + fedoraUrl);
        }
        FedoraAPIM apim;
        try {
            apim = fedora.getAPIM();
        } catch (Exception e) {
            throw new FdcException("could not create fedora APIM:" + e.getMessage());
        }

        //get the parameters from the request
        String pId = req.getParameter("pid");
        String dsId = req.getParameter("dsid");
        String fileUri = req.getParameter("fileUri");

        boolean useNewName = false;
        if ("true".equals(req.getParameter("useNewName"))) {
            useNewName = true;
        }
        if (pId == null || pId.length() == 0)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing pid parameter)");
        if (dsId == null || dsId.length() == 0)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing dsid parameter)");
        if (fileUri == null || fileUri.length() == 0)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing fileUri parameter)");

        FileItem fileRes = req.getFileItem("fileRes");
        if (fileRes == null)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing fileRes)");

        //check if file individual has a fedora:PID for a data stream
        VitroRequest vreq = new VitroRequest(rawRequest);
        IndividualDao iwDao = vreq.getWebappDaoFactory().getIndividualDao();
        Individual fileEntity = iwDao.getIndividualByURI(fileUri);

        //check if logged in
        //TODO: check if logged in

        //check if user is allowed to edit datastream
        //TODO:check if can edit datastream

        //check if digital object and data stream exist in fedora
        Datastream ds = apim.getDatastream(pId, dsId, null);
        if (ds == null)
            throw new FdcException(
                    "There was no datastream in the " + "repository for " + pId + " " + DEFAULT_DSID);

        //upload to temp holding area
        String originalName = fileRes.getName();
        String name = originalName.replaceAll("[,+\\\\/$%^&*#@!<>'\"~;]", "_");
        name = name.replace("..", "_");
        name = name.trim().toLowerCase();

        String saveLocation = baseDirectoryForFiles + File.separator + name;
        String savedName = name;
        int next = 0;
        boolean foundUnusedName = false;
        while (!foundUnusedName) {
            File test = new File(saveLocation);
            if (test.exists()) {
                next++;
                savedName = name + '(' + next + ')';
                saveLocation = baseDirectoryForFiles + File.separator + savedName;
            } else {
                foundUnusedName = true;
            }
        }

        File uploadedFile = new File(saveLocation);

        try {
            fileRes.write(uploadedFile);
        } catch (Exception ex) {
            log.error("Unable to save POSTed file. " + ex.getMessage());
            throw new FdcException("Unable to save file to the disk. " + ex.getMessage());
        }

        //upload to temp area on fedora
        File file = new File(saveLocation);
        String uploadFileUri = fedora.uploadFile(file);
        // System.out.println("Fedora upload temp = upload file uri is " + uploadFileUri);
        String md5 = md5hashForFile(file);
        md5 = md5.toLowerCase();

        //make change to data stream on fedora
        apim.modifyDatastreamByReference(pId, dsId, null, null, fileRes.getContentType(), null, uploadFileUri,
                "MD5", null, null, false);

        String checksum = apim.compareDatastreamChecksum(pId, dsId, null);

        //update properties like checksum, file size, and content type

        WebappDaoFactory wdf = vreq.getWebappDaoFactory();
        DataPropertyStatement dps = null;
        DataProperty contentType = wdf.getDataPropertyDao().getDataPropertyByURI(this.contentTypeProperty);
        if (contentType != null) {
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, contentType);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(contentType.getURI());
            dps.setData(fileRes.getContentType());
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
        }

        DataProperty fileSize = wdf.getDataPropertyDao().getDataPropertyByURI(this.fileSizeProperty);
        if (fileSize != null) {
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, fileSize);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(fileSize.getURI());
            dps.setData(Long.toString(fileRes.getSize()));
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
            //System.out.println("Updated file size with " + fileRes.getSize());
        }

        DataProperty checksumDp = wdf.getDataPropertyDao().getDataPropertyByURI(this.checksumDataProperty);
        if (checksumDp != null) {
            //System.out.println("Checksum data property is also not null");
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, checksumDp);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(checksumDp.getURI());
            dps.setData(checksum);
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
        }

        //I'm leaving if statement out for now as the above properties are obviously being replaced as well
        //if( "true".equals(useNewName)){
        //Do we need to encapuslate in this if OR is this path always for replacing a file
        //TODO: Put in check to see if file name has changed and only execute these statements if file name has changed
        DataProperty fileNameProperty = wdf.getDataPropertyDao().getDataPropertyByURI(this.fileNameProperty);
        if (fileNameProperty != null) {
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, fileNameProperty);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(fileNameProperty.getURI());
            dps.setData(originalName); //This follows the pattern of the original file upload - the name returned from the uploaded file object
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
            //System.out.println("File name property is not null = " + fileNameProperty.getURI() + " updating to " + originalName);
        } else {
            //System.out.println("file name property is null");
        }

        //Need to also update the check sum node - how would we do that
        //Find checksum node related to this particular file uri, then go ahead and update two specific fields

        List<ObjectPropertyStatement> csNodeStatements = fileEntity.getObjectPropertyMap()
                .get(this.checksumNodeProperty).getObjectPropertyStatements();
        if (csNodeStatements.size() == 0) {
            System.out.println("No object property statements correspond to this property");
        } else {
            ObjectPropertyStatement cnodeStatement = csNodeStatements.get(0);
            String cnodeUri = cnodeStatement.getObjectURI();
            //System.out.println("Checksum node uri is " + cnodeUri);

            Individual checksumNodeObject = iwDao.getIndividualByURI(cnodeUri);

            DataProperty checksumDateTime = wdf.getDataPropertyDao()
                    .getDataPropertyByURI(this.checksumNodeDateTimeProperty);
            if (checksumDateTime != null) {
                String newDatetime = sessionOntModel.createTypedLiteral(new DateTime()).getString();
                //Review how to update date time
                wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(
                        checksumNodeObject, checksumDateTime);
                dps = new DataPropertyStatementImpl();
                dps.setIndividualURI(checksumNodeObject.getURI());
                dps.setDatapropURI(checksumDateTime.getURI());
                dps.setData(newDatetime);
                wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);

            }
            DataProperty checksumNodeValue = wdf.getDataPropertyDao()
                    .getDataPropertyByURI(this.checksumDataProperty);
            if (checksumNodeValue != null) {
                wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(
                        checksumNodeObject, checksumNodeValue);
                dps = new DataPropertyStatementImpl();
                dps.setIndividualURI(checksumNodeObject.getURI());
                dps.setDatapropURI(checksumNodeValue.getURI());
                dps.setData(checksum); //Same as fileName above - change if needed
                wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
            }

        }

        //Assumes original entity name is equal to the location - as occurs with regular file upload
        String originalEntityName = fileEntity.getName();
        if (originalEntityName != originalName) {
            //System.out.println("Setting file entity to name of uploaded file");
            fileEntity.setName(originalName);
        } else {
            //System.out.println("Conditional for file entity name and uploaded name is saying same");
        }
        iwDao.updateIndividual(fileEntity);
        //}

        req.setAttribute("fileUri", fileUri);
        req.setAttribute("originalFileName", fileEntity.getName());
        req.setAttribute("checksum", checksum);
        if ("true".equals(useNewName)) {
            req.setAttribute("useNewName", "true");
            req.setAttribute("newFileName", originalName);
        } else {
            req.setAttribute("newFileName", fileEntity.getName());
        }

        //forward to form     
        req.setAttribute("bodyJsp", "/fileupload/datastreamModificationSuccess.jsp");
        RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
        rd.forward(req, res);
    } catch (FdcException ex) {
        rawRequest.setAttribute("errors", ex.getMessage());
        RequestDispatcher rd = rawRequest.getRequestDispatcher("/edit/fileUploadError.jsp");
        rd.forward(rawRequest, res);
        return;
    }
}

From source file:es.sm2.openppm.front.servlets.ProjectServlet.java

/**
 * /*from   www  .j  av a2 s .  c om*/
 * @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
private void uploadFileSystem(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    // Request
    //
    int idProject = Integer.parseInt(getMultipartField(Documentproject.PROJECT));
    int docId = Integer.parseInt(getMultipartField(Documentproject.IDDOCUMENTPROJECT));
    String docType = getMultipartField(Documentproject.TYPE);
    String oldName = StringPool.BLANK;
    String contentComment = getMultipartField(Documentproject.CONTENTCOMMENT, StringPool.UTF8);
    String creationContact = getUser(req).getContact().getFullName();
    Date creationDate = DateUtil.getCalendar().getTime();
    Integer idClosureCheckProject = ValidateUtil
            .isNotNull(getMultipartField(Closurecheckproject.IDCLOSURECHECKPROJECT))
                    ? Integer.parseInt(getMultipartField(Closurecheckproject.IDCLOSURECHECKPROJECT))
                    : null;
    Integer idTimeline = ValidateUtil.isNotNull(getMultipartField(Timeline.IDTIMELINE))
            ? Integer.parseInt(getMultipartField(Timeline.IDTIMELINE))
            : null;

    // Date format
    SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.TIME_PATTERN);

    JSONObject docJSON = new JSONObject();
    String errorFile = StringPool.BLANK;

    PrintWriter out = resp.getWriter();

    resp.setContentType("text/plain");

    Documentproject doc = new Documentproject();

    // Declare logic
    DocumentprojectLogic documentprojectLogic = new DocumentprojectLogic(getSettings(req),
            getResourceBundle(req));
    ProjectLogic projectLogic = new ProjectLogic(getSettings(req));

    try {
        FileItem dataFile = getMultipartFields().get("file");

        // Update   
        if (docId != -1) {

            doc = documentprojectLogic.findById(docId, false);

            oldName = doc.getIdDocumentProject() + StringPool.UNDERLINE
                    + (doc.getName().lastIndexOf("\\") != -1
                            ? StringUtils
                                    .formatting(doc.getName().substring(doc.getName().lastIndexOf("\\") + 1))
                            : StringUtils.formatting(doc.getName()));
        }

        // if new file set data
        if (dataFile != null && dataFile.getSize() > 0) {

            doc.setName(dataFile.getName().lastIndexOf("\\") != -1
                    ? dataFile.getName().substring(dataFile.getName().lastIndexOf("\\") + 1)
                    : dataFile.getName());
            doc.setExtension(FilenameUtils.getExtension(dataFile.getName()));
            doc.setMime(dataFile.getContentType());
        }

        Project project = projectLogic.consProject(idProject);

        // Set another data
        doc.setProject(project);
        doc.setType(docType);
        doc.setContentComment(contentComment);
        doc.setCreationContact(creationContact);
        doc.setCreationDate(creationDate);

        // Logic
        doc = documentprojectLogic.save(doc);

        if (dataFile != null && dataFile.getSize() > 0) {

            String newName = doc.getIdDocumentProject() + StringPool.UNDERLINE
                    + (dataFile.getName().lastIndexOf("\\") != -1
                            ? StringUtils.formatting(
                                    dataFile.getName().substring(dataFile.getName().lastIndexOf("\\") + 1))
                            : StringUtils.formatting(dataFile.getName()));

            // TODO jordi.ripoll - 12/05/2015 - los archivos se guardaban en esta ruta - al migrar reestructurar codigo
            String dirBySetting = SettingUtil.getString(getSettings(req),
                    Settings.SETTING_PROJECT_DOCUMENT_FOLDER, Settings.DEFAULT_PROJECT_DOCUMENT_FOLDER);

            // Create folder by project and status
            //
            String docFolder = dirBySetting.concat(File.separator
                    + StringUtils.formatting(project.getChartLabel()) + StringPool.UNDERLINE + idProject);

            File folderProject = new File(docFolder);

            if (!folderProject.isDirectory()) {
                // Create dir project
                folderProject.mkdir();
            }

            // Update doc folder
            docFolder = docFolder.concat(File.separator + docType);

            File folderProjectStatus = new File(docFolder);

            if (!folderProjectStatus.isDirectory()) {
                // Create dir status
                folderProjectStatus.mkdir();
            }

            File file = new File(docFolder, newName);

            // Validate file and permissions
            errorFile = documentprojectLogic.validateFile(new File(docFolder));

            // Save file
            dataFile.write(file);

            if (!oldName.equals(newName)) {

                file = new File(dirBySetting, oldName);

                // Search in new path
                if (!file.exists()) {
                    file = new File(docFolder, oldName);
                }

                // Delete old file
                file.delete();
            }
        }

        // Set document into closure check project
        if (idClosureCheckProject != null) {

            // Declare logic
            ClosurecheckprojectLogic closurecheckprojectLogic = new ClosurecheckprojectLogic();

            closurecheckprojectLogic.saveDocument(idClosureCheckProject, doc);

            // Response
            docJSON.put(Closurecheckproject.IDCLOSURECHECKPROJECT, idClosureCheckProject);
        }
        // Set document into timeline
        else if (idTimeline != null) {

            // Declare logic
            TimelineLogic timelineLogic = new TimelineLogic(getSettings(req), getResourceBundle(req));

            timelineLogic.saveDocument(idTimeline, doc);

            // Response
            docJSON.put(Timeline.IDTIMELINE, idTimeline);
        }

        // Response
        //
        docJSON.put(Documentproject.IDDOCUMENTPROJECT, doc.getIdDocumentProject());
        docJSON.put(Documentproject.TYPE, getResourceBundle(req).getString("documentation." + doc.getType()));
        docJSON.put(Documentproject.NAME,
                (doc.getName().lastIndexOf("\\") != -1
                        ? doc.getName().substring(doc.getName().lastIndexOf("\\") + 1)
                        : doc.getName()));
        docJSON.put(Documentproject.CONTENTCOMMENT, doc.getContentComment());
        docJSON.put(Documentproject.CREATIONCONTACT, doc.getCreationContact());
        docJSON.put(Documentproject.CREATIONDATE, dateFormat.format(doc.getCreationDate()));
        docJSON.put("documentType", DocumentType.FILE_SYSTEM.getName());

        if (docId == -1) {
            infoCreated(getResourceBundle(req), docJSON, "document"); //TODO esto no funciona LA CULPA ES DEL METODO AJAX de subir documento que es diferente
        } else {
            infoUpdated(getResourceBundle(req), docJSON, "document");
        }

        // Add messages file error
        if (ValidateUtil.isNotNull(errorFile)) {
            docJSON.put(StringPool.InfoType.ERROR.getName(), errorFile);
        }

        out.print(docJSON);
    } catch (Exception e) {

        try {
            documentprojectLogic.delete(doc);
        } catch (Exception e1) {
            ExceptionUtil.evalueExceptionJX(out, req, getResourceBundle(req), LOGGER, e1);
        }

        ExceptionUtil.evalueExceptionJX(out, req, getResourceBundle(req), LOGGER, e);
    } finally {
        out.close();
    }
}