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

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

Introduction

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

Prototype

void write(File file) throws Exception;

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:AtualizarUser.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    String caminho;// w  w  w .jav  a 2s.c  o  m
    if (isMultipart) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    //                                            items.get(0).getString();
                    req.setAttribute(item.getFieldName(), item.getString());
                    resp.getWriter()
                            .println("No  campo file" + this.getServletContext().getRealPath("/img"));
                    resp.getWriter().println("Name campo: " + item.getFieldName());
                    resp.getWriter().println("Value campo: " + item.getString());

                    req.setAttribute(item.getFieldName(), item.getString());
                } else {
                    //caso seja um campo do tipo file

                    resp.getWriter().println("Campo file");
                    resp.getWriter().println("Name:" + item.getFieldName());
                    resp.getWriter().println("nome arquivo :" + item.getName());
                    resp.getWriter().println("Size:" + item.getSize());
                    resp.getWriter().println("ContentType:" + item.getContentType());
                    if (item.getName() == "" || item.getName() == null) {
                        caminho = "img\\usuario.jpg";
                    } else {
                        caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName();
                        resp.getWriter().println("Caminho: " + caminho);
                        File uploadedFile = new File(
                                "E:\\Documentos\\NetBeansProjects\\SisLivros\\web\\" + caminho);
                        item.write(uploadedFile);

                    }

                    req.setAttribute("caminho", caminho);
                    req.getRequestDispatcher("AtualizarDadosUser").forward(req, resp);
                }

            }
        } catch (Exception e) {
            //            resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage());
        }
    }

}

From source file:com.krawler.svnwebclient.util.Uploader.java

public void doPost(HttpServletRequest request, HttpServletResponse responce, String destinationDirectory,
        String tempDirectory) throws SessionExpiredException {
    File tempDir = new File(tempDirectory);
    String sep = StorageHandler.GetFileSeparator();
    if (!tempDir.exists()) {
        tempDir.mkdirs();/*from   www  .j a va  2 s.  c  o  m*/
    }
    DiskFileUpload fu = new DiskFileUpload();
    // maximum size before a FileUploadException will be thrown
    fu.setSizeMax(-1);
    // maximum size that will be stored in memory
    fu.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    fu.setRepositoryPath(tempDirectory);
    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        Logger.getInstance(Uploader.class).error(e, e);
    }
    String docid1 = null;
    String docownerid = null;
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        FileItem fi1 = (FileItem) k.next();
        try {
            if (fi1.getFieldName().toString().equals("docid")) {
                docid1 = new String(fi1.getString().getBytes(), "UTF8");
            }
            if (fi1.getFieldName().toString().equals("docownerid")) {
                docownerid = new String(fi1.getString().getBytes(), "UTF8");
            }
        } catch (UnsupportedEncodingException e) {
            // Logger.getInstance(Uploader.class).error(e, e);
        }
    }
    if (docid1.equals("")) {
        docid1 = UUID.randomUUID().toString();
        this.setFlagType(true);
        docownerid = AuthHandler.getUserid(request);
    } else {
        this.setFlagType(false);
    }
    try {
        if (docownerid.equalsIgnoreCase("my")) {
            docownerid = AuthHandler.getUserid(request);
        }
        destinationDirectory = com.krawler.esp.handlers.StorageHandler.GetDocStorePath() + sep + docownerid;
    } catch (ConfigurationException ex) {
        this.isUploaded = false;
        this.errorMessage = "Problem occurred while uploading file";
        return;
    }
    File destDir = new File(destinationDirectory);
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    this.parameters.put("destinationDirectory", destinationDirectory);
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();

        /*
         * try{ String docid1 = fi.getString("docid"); }catch(Exception e){}
         */
        if (fi.isFormField()) {
            try {
                if (fi.getFieldName().toString().equals("docid")
                        && new String(fi.getString().getBytes(), "UTF8").equals("")) {
                    this.parameters.put(fi.getFieldName(), docid1);
                } else {
                    this.parameters.put(fi.getFieldName(), new String(fi.getString().getBytes(), "UTF8"));
                }
            } catch (UnsupportedEncodingException e) {
                Logger.getInstance(Uploader.class).error(e, e);
            }
        } else {
            // filename on the client
            String fileName = null;

            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                // org.tmatesoft.svn.core.internal.wc.SVNFileUtil.isExecutable(fi);
                String filext = "";
                if (fileName.contains("."))
                    filext = fileName.substring(fileName.lastIndexOf("."));

                if (fi.getSize() != 0) {
                    this.isUploaded = true;

                    // write the file
                    File uploadFile = new File(
                            destinationDirectory + sep + FileUtil.getLastPathElement(docid1 + filext));
                    fi.write(uploadFile);
                    this.parameters.put("svnName", uploadFile.getName());
                    if (filext.equals("")) {
                        this.parameters.put("fileExt", filext);
                    } else {
                        this.parameters.put("fileExt", filext.substring(1));
                    }
                } else {
                    this.isUploaded = false;
                    this.errorMessage = "Cannot upload a 0 byte file";
                }
            } catch (Exception e) {
                this.isUploaded = false;
                this.errorMessage = "Problem occurred while uploading file";
                Logger.getInstance(Uploader.class).error(e, e);
            }
            this.parameters.put(FormParameters.FILE_NAME, FileUtil.getLastPathElement(fileName));
        }
    }
}

From source file:cdc.util.Upload.java

public boolean anexos(HttpServletRequest request) throws Exception {
    request.setCharacterEncoding("ISO-8859-1");
    if (ServletFileUpload.isMultipartContent(request)) {
        int cont = 0;
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List fileItemsList = null;
        try {//from   w  w w .j a va2s .  co m
            fileItemsList = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String optionalFileName = "";
        FileItem fileItem = null;
        Iterator it = fileItemsList.iterator();
        do {
            //cont++;
            FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
                if (fileItemTemp.getFieldName().equals("file")) {
                    optionalFileName = fileItemTemp.getString();
                }
                parametros.put(fileItemTemp.getFieldName(), fileItemTemp.getString());
            } else {
                fileItem = fileItemTemp;
            }
            if (cont != (fileItemsList.size())) {
                if (fileItem != null) {
                    String fileName = fileItem.getName();
                    if (fileItem.getSize() > 0) {
                        if (optionalFileName.trim().equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                        } else {
                            fileName = optionalFileName;
                        }
                        String dirName = request.getServletContext().getRealPath(pasta);
                        File saveTo = new File(dirName + "/" + fileName);
                        //verificando se a pasta existe. Caso contrrio, criar ela
                        File pasta = new File(dirName);
                        if (!pasta.exists())
                            pasta.mkdirs();//criando a pasta

                        parametros.put("foto", fileName);

                        try {
                            fileItem.write(saveTo);//Escrevendo o arquivo temporrio no diretrio correto
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cont++;
        } while (it.hasNext());
        return true;
    } else {
        return false;
    }
}

From source file:de.fau.amos.FileUpload.java

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

    String pathInfo = request.getPathInfo();
    System.out.println("called fileupload: " + pathInfo);
    boolean isImportProductionData = pathInfo != null && pathInfo.startsWith("/importProductionData");
    boolean isImportEnergyData = pathInfo != null && pathInfo.startsWith("/importEnergyData");

    if (ServletFileUpload.isMultipartContent(request)) {
        try {/*  w  w w  .  j  a va  2 s.  c  o  m*/
            List<FileItem> list = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem fi : list) {
                if (!fi.isFormField()) {
                    String rand = "";
                    for (int i = 0; i < 6; i++) {
                        rand += (int) (Math.random() * 10);
                    }
                    String plantId = "";
                    if (isImportEnergyData || isImportProductionData) {
                        plantId = request.getPathInfo().replace((isImportEnergyData ? "/importEnergyData"
                                : (isImportProductionData ? "/importProductionData" : "")), "");
                    }
                    if (plantId == null || plantId.length() == 0) {
                        plantId = "";
                        //                  }else{
                        //                     plantId="_"+plantId;
                    }
                    String name = new File(rand + "_" + fi.getName()).getName()
                            + (isImportEnergyData ? "_impED" + plantId
                                    : (isImportProductionData ? "_impPD" + plantId : ""));

                    File folder = null;
                    if (isImportEnergyData || isImportProductionData) {
                        folder = new File(System.getProperty("userdir.location"), "import");
                    } else {
                        folder = new File(System.getProperty("userdir.location"), "uploads");
                    }
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    fi.write(new File(folder, name));
                }
            }

            request.setAttribute("message", "File uploaded successfully");
        } catch (Exception e) {
            request.setAttribute("errorMessage", "File upload failed!");
        }

    } else {
        request.setAttribute("errorMessage", "Something went wrong.");
    }

    if (isImportEnergyData || isImportProductionData) {
        //         request.setAttribute("plant",request.getPathInfo().replace("/import",""));
        //         request.getRequestDispatcher("/intern/import.jsp").forward(request, response);
        response.sendRedirect(request.getContextPath() + "/intern/import.jsp");
    } else {
        response.sendRedirect(request.getContextPath() + "/intern/funktion3.jsp");
    }

}

From source file:hu.sztaki.lpds.pgportal.portlets.workflow.WorkflowUploadPortlet.java

@Override
protected void doUpload(ActionRequest request, ActionResponse response) {
    PortletContext context = getPortletContext();
    context.log("[FileUploadPortlet] doUpload() called");

    try {//from   w w w . jav  a 2  s  .  c  o m
        DiskFileItemFactory factory = new DiskFileItemFactory();
        PortletFileUpload pfu = new PortletFileUpload(factory);
        pfu.setSizeMax(uploadMaxSize); // Maximum upload size
        pfu.setProgressListener((ProgressListener) new FileUploadProgressListener());

        PortletSession ps = request.getPortletSession();
        if (ps.getAttribute("uploads", ps.APPLICATION_SCOPE) == null)
            ps.setAttribute("uploads", new Hashtable<String, ProgressListener>());

        //get the FileItems
        String fieldName = null;

        List fileItems = pfu.parseRequest(request);
        Iterator iter = fileItems.iterator();
        File serverSideFile = null;
        Hashtable h = new Hashtable(); //fileupload
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // retrieve hidden parameters if item is a form field
            if (item.isFormField()) {
                fieldName = item.getFieldName();
                if ("newGrafName".equals(fieldName))
                    h.put("newGrafName", item.getString());
                if ("newAbstName".equals(fieldName))
                    h.put("newAbstName", item.getString());
                if ("newRealName".equals(fieldName))
                    h.put("newRealName", item.getString());
            } else { // item is not a form field, do file upload
                Hashtable<String, ProgressListener> tmp = (Hashtable<String, ProgressListener>) ps
                        .getAttribute("uploads");//,ps.APPLICATION_SCOPE
                pfu.setProgressListener((ProgressListener) new FileUploadProgressListener());

                String s = item.getName();
                s = FilenameUtils.getName(s);
                ProgressListener pl = pfu.getProgressListener();
                tmp.put(s, pl);
                ps.setAttribute("uploads", tmp);

                String tempDir = System.getProperty("java.io.tmpdir") + "/uploads/" + request.getRemoteUser();
                File f = new File(tempDir);
                if (!f.exists())
                    f.mkdirs();
                serverSideFile = new File(tempDir, s);
                item.write(serverSideFile);
                item.delete();
                context.log("[FileUploadPortlet] - file " + s + " uploaded successfully to " + tempDir);
            }
        }
        // file upload to storage
        try {
            ServiceType st = InformationBase.getI().getService("wfs", "portal", new Hashtable(), new Vector());
            h.put("senderObj", "ZipFileSender");
            h.put("portalURL", PropertyLoader.getInstance().getProperty("service.url"));
            h.put("wfsID", st.getServiceUrl());
            h.put("userID", request.getRemoteUser());

            Hashtable hsh = new Hashtable();
            //                    st = InformationBase.getI().getService("storage", "portal", hsh, new Vector());
            //                    hsh.put("url", "http://localhost:8080/storage");
            st = InformationBase.getI().getService("storage", "portal", hsh, new Vector());
            PortalStorageClient psc = (PortalStorageClient) Class.forName(st.getClientObject()).newInstance();
            psc.setServiceURL(st.getServiceUrl());
            psc.setServiceID("/receiver");
            if (serverSideFile != null)
                psc.fileUpload(serverSideFile, "fileName", h);
        } catch (Exception ex) {
            response.setRenderParameter("full", "error.upload");
            ex.printStackTrace();
            return;
        }
        ps.removeAttribute("uploads", ps.APPLICATION_SCOPE);

    } catch (FileUploadException fue) {
        response.setRenderParameter("full", "error.upload");

        fue.printStackTrace();
        context.log("[FileUploadPortlet] - failed to upload file - " + fue.toString());
        return;
    } catch (Exception e) {
        e.printStackTrace();
        response.setRenderParameter("full", "error.exception");
        context.log("[FileUploadPortlet] - failed to upload file - " + e.toString());
        return;
    }
    response.setRenderParameter("full", "action.succesfull");
}

From source file:edu.uniminuto.servlets.GuardarDisco.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*www.j  av  a  2  s .  c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String nombre = "";
    long precio = 0;
    int anhio = 0;
    short genero = 1;
    int interprete = 1;

    //        String nombre = getParameter(request, "nombre");
    //        long precio = Long.valueOf(getParameter(request, "precio"));
    //        int anhio = Integer.valueOf(getParameter(request, "anhio"));
    //
    //        int genero = Integer.valueOf(getParameter(request, "genero"));
    //        int interprete = Integer.valueOf(getParameter(request, "interprete"));

    String url = "";
    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String imagen = "images/";

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, new File("c;//tmp"));

        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

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

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                if (item.getFieldName().equals("nombre")) {
                    nombre = item.getString();
                } else if (item.getFieldName().equals("anhio")) {
                    anhio = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("genero")) {
                    genero = Short.valueOf(item.getString());
                } else if (item.getFieldName().equals("interprete")) {
                    interprete = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("precio")) {
                    precio = Long.valueOf(item.getString());
                }

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

                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                imagen = imagen + fileName;
                File uploadedFile = new File(RUTA + fileName);

                item.write(uploadedFile);
                //                    } else {
                //                        
                //                    }
            }
        }

        java.util.Calendar cl = java.util.Calendar.getInstance();
        cl.set(anhio, 0, 0, 0, 0, 0);

        Disco disco = new Disco();
        disco.setGenero(generoFacade.find(genero));
        disco.setInterprete(interpreteFacade.find(interprete));
        disco.setNombre(nombre);
        disco.setImagen(imagen);
        disco.setAnhio(cl.getTime());

        discoFacade.create(disco);

        if (disco.getId() != null) {

            Discopropietario dp = new Discopropietario();
            dp.setDisco(disco);
            dp.setPropietario((Persona) request.getSession().getAttribute("usuario"));
            dp.setPrecio(precio);
            dp.setVendido(false);

            dpFacade.create(dp);

            url = "disco?id=" + disco.getId();

        } else {
            url = "fdisco?nombre=" + nombre + "&precio=" + precio + "&anhio=" + anhio + "&genero=" + genero
                    + "&interprete=" + interprete;
        }

    } catch (FileUploadException ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    }

    response.sendRedirect(url);

}

From source file:com.manning.cmis.theblend.servlets.AddServlet.java

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

    // check for multipart content
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        // we expected content -> return to add page
        dispatch("add.jsp", "Add something new. The Blend.", request, response);
    }//  w  w w. java 2s.c  om

    Map<String, Object> properties = new HashMap<String, Object>();
    File uploadedFile = null;
    String parentId = null;
    String parentPath = null;
    ObjectId newId = null;

    // process the request
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(50 * 1024 * 1024);

        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);

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

            if (item.isFormField()) {
                String name = item.getFieldName();

                if (PARAM_PARENT_ID.equalsIgnoreCase(name)) {
                    parentId = item.getString();
                } else if (PARAM_PARENT_PATH.equalsIgnoreCase(name)) {
                    parentPath = item.getString();
                } else if (PARAM_TYPE_ID.equalsIgnoreCase(name)) {
                    properties.put(PropertyIds.OBJECT_TYPE_ID, item.getString());
                }
            } else {
                String name = item.getName();
                if (name == null) {
                    name = "file";
                } else {
                    // if the browser provided a path instead of a file name,
                    // strip off the path
                    int x = name.lastIndexOf('/');
                    if (x > -1) {
                        name = name.substring(x + 1);
                    }
                    x = name.lastIndexOf('\\');
                    if (x > -1) {
                        name = name.substring(x + 1);
                    }

                    name = name.trim();
                    if (name.length() == 0) {
                        name = "file";
                    }
                }

                properties.put(PropertyIds.NAME, name);

                uploadedFile = File.createTempFile("blend", "tmp");
                item.write(uploadedFile);
            }
        }
    } catch (Exception e) {
        throw new TheBlendException("Upload failed: " + e, e);
    }

    if (uploadedFile == null) {
        throw new TheBlendException("No content!");
    }

    try {
        // prepare the content stream
        ContentStream contentStream = null;
        try {
            String objectTypeId = (String) properties.get(PropertyIds.OBJECT_TYPE_ID);
            contentStream = prepareContentStream(session, uploadedFile, objectTypeId, properties);
        } catch (Exception e) {
            throw new TheBlendException("Upload failed: " + e, e);
        }

        // find the parent folder
        // (we don't deal with unfiled documents here)
        Folder parent = null;
        if (parentId != null) {
            parent = CMISHelper.getFolder(session, parentId, CMISHelper.LIGHT_OPERATION_CONTEXT,
                    "parent folder");
        } else {
            parent = CMISHelper.getFolderByPath(session, parentPath, CMISHelper.LIGHT_OPERATION_CONTEXT,
                    "parent folder");
        }

        // create the document
        try {
            newId = session.createDocument(properties, parent, contentStream, null);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Could not create document: " + cbe.getMessage(), cbe);
        } finally {
            try {
                contentStream.getStream().close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    } finally {
        // delete temp file
        uploadedFile.delete();
    }

    // show the newly created document
    redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response);
}

From source file:com.stratelia.silverpeas.versioningPeas.servlets.VersioningRequestRouter.java

/**
 * Process request form/*from w  w w.  j av a2 s.  com*/
 * @param request
 * @param versioningSC
 * @return
 * @throws Exception
 * @throws IOException
 */
private void saveNewDocument(HttpServletRequest request, VersioningSessionController versioningSC)
        throws Exception {
    SilverTrace.debug("versioningPeas", "VersioningRequestRooter.saveNewDocument()",
            "root.MSG_GEN_ENTER_METHOD");
    int majorNumber = 0;
    int minorNumber = 1;
    String type = "dummy";
    String physicalName = "dummy";
    String logicalName = "dummy";
    String mimeType = "dummy";
    File dir = null;
    int size = 0;
    DocumentPK docPK = new DocumentPK(-1, versioningSC.getComponentId());
    if (!StringUtil.isDefined(request.getCharacterEncoding())) {
        request.setCharacterEncoding("UTF-8");
    }
    String encoding = request.getCharacterEncoding();

    List<FileItem> items = FileUploadUtil.parseRequest(request);
    String comments = FileUploadUtil.getParameter(items, "comments", "", encoding);
    int versionType = Integer.parseInt(FileUploadUtil.getParameter(items, "versionType", "0", encoding));

    FileItem fileItem = FileUploadUtil.getFile(items, "file_upload");
    boolean runOnUnix = !FileUtil.isWindows();
    logicalName = fileItem.getName();
    if (logicalName != null) {

        if (runOnUnix) {
            logicalName = logicalName.replace('\\', File.separatorChar);
        }

        logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length());
        type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length());
        physicalName = new Long(new Date().getTime()).toString() + "." + type;
        mimeType = FileUtil.getMimeType(logicalName);
        if (!StringUtil.isDefined(mimeType)) {
            mimeType = "unknown";
        }
        dir = new File(versioningSC.createPath(versioningSC.getComponentId(), null) + physicalName);
        size = new Long(fileItem.getSize()).intValue();
        fileItem.write(dir);
    }

    if (versionType == VersioningSessionController.PUBLIC_VERSION) {
        majorNumber = 1;
        minorNumber = 0;
    }
    if (size == 0) {
        majorNumber = 0;
        minorNumber = 0;
    }
    DocumentVersion documentVersion = new DocumentVersion(null, docPK, majorNumber, minorNumber,
            Integer.parseInt(versioningSC.getUserId()), new Date(), comments, versionType,
            DocumentVersion.STATUS_VALIDATION_NOT_REQ, physicalName, logicalName, mimeType, size,
            versioningSC.getComponentId());

    boolean addXmlForm = !isXMLFormEmpty(versioningSC, items);
    if (addXmlForm) {
        documentVersion.setXmlForm(versioningSC.getXmlForm());
    }

    // Document
    docPK = new DocumentPK(-1, versioningSC.getComponentId());

    String name = FileUploadUtil.getParameter(items, "name", "", encoding);
    String publicationId = FileUploadUtil.getParameter(items, "publicationId", "-1", encoding);
    String description = FileUploadUtil.getParameter(items, "description", "", encoding);

    PublicationPK pubPK = new PublicationPK(publicationId, versioningSC.getComponentId());
    Document document = new Document(docPK, pubPK, name, description, Document.STATUS_CHECKINED, -1, new Date(),
            null, versioningSC.getComponentId(), null, null, 0,
            Integer.parseInt(VersioningSessionController.WRITERS_LIST_SIMPLE));

    String docId = versioningSC.createDocument(document, documentVersion).getId();

    if (addXmlForm) {
        // Save additional informations
        saveXMLData(versioningSC, documentVersion.getPk(), items);
    }

    versioningSC.setEditingDocument(document);
    versioningSC.setFileRights();
    versioningSC.updateWorkList(document);
    versioningSC.updateDocument(document);

    // Specific case: 3d file to convert by Actify Publisher
    ResourceLocator attachmentSettings = new ResourceLocator(
            "com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean actifyPublisherEnable = attachmentSettings.getBoolean("ActifyPublisherEnable", false);
    if (actifyPublisherEnable) {
        versioningSC.saveFileForActify(docId, documentVersion, attachmentSettings);
    }

    SilverTrace.debug("versioningPeas", "VersioningRequestRooter.saveNewDocument()",
            "root.MSG_GEN_EXIT_METHOD");
}

From source file:it.infn.mib.AndreaPortlet.java

/**
 * This method is called when the user specifies a input file to upload
 * The file will be saved first into /tmp directory and then its content
 * stored into the corresponding String variable
 * Before to submit the job the String value will be stored in the 
 * proper job inputSandbox file//from  w w  w. j  a v a2  s .  c o m
 * 
 * @param item
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void processInputFile(FileItem item, AppInput appInput) {
    // Determin the filename
    String fileName = item.getName();
    if (!fileName.equals("")) {
        // Determine the fieldName
        String fieldName = item.getFieldName();

        // Create a filename for the uploaded file
        String theNewFileName = "/tmp/" + appInput.timestamp + "_" + appInput.username + "_" + fileName;
        File uploadedFile = new File(theNewFileName);
        _log.info("Uploading file: '" + fileName + "' into '" + theNewFileName + "'");
        try {
            item.write(uploadedFile);
        } catch (Exception e) {
            _log.error("Caught exception while uploading file: 'file_inputFile'");
        }
        // File content has to be inserted into a String variables:
        //   inputFileName -> inputFileText
        try {
            if (fieldName.equals("file_inputFile")) {
                appInput.inputFileText = updateString(theNewFileName);
                // Other params can be added as below ...
                //else if (fieldName.equals("..."))
                //   ...=updateString(theNewFileName);
            } else {
                // Never happens
            }
        } catch (Exception e) {
            _log.error("Caught exception while processing strings: '" + e.toString() + "'");
        }
    } // if
}

From source file:com.controller.UploadLogo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   www . j av a 2  s .  c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    getSqlMethodsInstance().session = request.getSession();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, uploadType = null;
    RequestDispatcher request_dispatcher = null;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        uploadPath = AppConstants.USER_LOGO;

        // Verify the content type
        String contentType = request.getContentType();

        if ((contentType.indexOf("multipart/form-data") >= 0)) {

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

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

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

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                boolean ch = fi.isFormField();

                if (!fi.isFormField()) {

                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    String uid = (String) getSqlMethodsInstance().session.getAttribute("EmailID");

                    int UID = getSqlMethodsInstance().getUserID(uid);
                    uploadPath = uploadPath + File.separator + UID + File.separator + "logo";

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

                    //                                int inStr = fileName.indexOf(".");
                    //                                String Str = fileName.substring(0, inStr);
                    //
                    //                                fileName = Str + "_" + UID + ".jpeg";
                    fileName = fileName + "_" + UID;
                    getSqlMethodsInstance().session.setAttribute("UID", UID);
                    getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName);
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    fi.write(storeFile);

                    getSqlMethodsInstance().updateUsers(UID, fileName);
                    out.println("Uploaded Filename: " + filePath + "<br>");
                }

            }
        }

    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));

        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
        getSqlMethodsInstance().closeConnection();
    }

}