Example usage for org.apache.commons.fileupload FileItemIterator hasNext

List of usage examples for org.apache.commons.fileupload FileItemIterator hasNext

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemIterator hasNext.

Prototype

boolean hasNext() throws FileUploadException, IOException;

Source Link

Document

Returns, whether another instance of FileItemStream is available.

Usage

From source file:lucee.runtime.type.scope.FormImpl.java

private void initializeMultiPart(PageContext pc, boolean scriptProteced) {
    // get temp directory
    Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory();
    Resource tempFile;/*from   ww w  .java2s.c  o  m*/

    // Create a new file upload handler
    final String encoding = getEncoding();
    FileItemFactory factory = tempDir instanceof File
            ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir)
            : new DiskFileItemFactory();

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding(encoding);
    //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest());

    HttpServletRequest req = pc.getHttpServletRequest();
    ServletRequestContext context = new ServletRequestContext(req) {
        public String getCharacterEncoding() {
            return encoding;
        }
    };

    // Parse the request
    try {
        FileItemIterator iter = upload.getItemIterator(context);
        //byte[] value;
        InputStream is;
        ArrayList<URLItem> list = new ArrayList<URLItem>();
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            is = IOUtil.toBufferedInputStream(item.openStream());
            if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) {
                list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false));
            } else {
                tempFile = tempDir.getRealResource(getFileName());
                fileItems.put(item.getFieldName().toLowerCase(),
                        new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName()));
                String value = tempFile.toString();
                IOUtil.copy(is, tempFile, true);

                list.add(new URLItem(item.getFieldName(), value, false));
            }
        }

        raw = list.toArray(new URLItem[list.size()]);
        fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
    } catch (Exception e) {

        //throw new PageRuntimeException(Caster.toPageException(e));
        fillDecodedEL(new URLItem[0], encoding, scriptProteced,
                pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
        initException = e;
    }
}

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

private Return<File> processFileUploadRequest(final FileItemIterator iter, final HttpSession session)
        throws IOException, FileUploadException {
    String returnVal = "Sorry! No Items To Process";
    final Map<String, String> parameterMap = new HashMap<String, String>();
    final File tempFile = getTempFile();
    String userFileExtension = null;

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        final String paramName = item.getFieldName();
        final InputStream stream = item.openStream();

        if (item.isFormField()) {//Parameter-Value
            final String paramValue = Streams.asString(stream);
            parameterMap.put(paramName, paramValue);
        }/*from w w  w  .  ja v a  2s .  c om*/
        if (!item.isFormField()) {
            final String usersFileName = item.getName();
            final int extensionDotIndex = usersFileName.lastIndexOf(".");
            userFileExtension = usersFileName.substring(extensionDotIndex + 1);
            final FileOutputStream fos = new FileOutputStream(tempFile);
            int byteCount = 0;
            while (true) {
                final int dataByte = stream.read();
                if (byteCount++ > UPLOAD_LIMIT) {
                    fos.close();
                    tempFile.delete();
                    return new ReturnImpl<File>(ExceptionCache.FILE_SIZE_EXCEPTION, "File Too Big!", true);
                }
                if (dataByte != -1) {
                    fos.write(dataByte);
                } else {
                    break;//break loop
                }
            }
            fos.close();
        }
    }

    final FileUploadListenerFace<File> fulf;

    /**
     * Implement this as a set of listeners. Why it wasn't done now is that, a new object of listener should be
     * created per request and added to the listener pool(list or array whatever).
     */
    switch (Integer.parseInt(parameterMap.get("type"))) {
    case 1:
        fulf = CDNProfilePhoto.getProfilePhotoCDNLocal();
        break;
    default:
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_SWITCH, "Unsupported Case", true);
    }
    if (tempFile == null) {
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION, "No File!", true);
    }

    return fulf.run(tempFile, parameterMap, userFileExtension, session);
}

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

private Return<File> processFileUploadRequest(final FileItemIterator iter, final HttpSession session)
        throws IOException, FileUploadException {
    String returnVal = "Sorry! No Items To Process";
    final Map<String, String> parameterMap = new HashMap<String, String>();
    final File tempFile = getTempFile();
    String userFileExtension = null;

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        final String paramName = item.getFieldName();
        final InputStream stream = item.openStream();

        if (item.isFormField()) {//Parameter-Value
            final String paramValue = Streams.asString(stream);
            parameterMap.put(paramName, paramValue);
        }/*from w w w  .  ja va  2 s  . c o m*/
        if (!item.isFormField()) {
            final String usersFileName = item.getName();
            final int extensionDotIndex = usersFileName.lastIndexOf(".");
            userFileExtension = usersFileName.substring(extensionDotIndex + 1);
            final FileOutputStream fos = new FileOutputStream(tempFile);
            int byteCount = 0;
            while (true) {
                final int dataByte = stream.read();
                if (byteCount++ > UPLOAD_LIMIT) {
                    fos.close();
                    tempFile.delete();
                    return new ReturnImpl<File>(ExceptionCache.FILE_SIZE_EXCEPTION, "File Too Big!", true);
                }
                if (dataByte != -1) {
                    fos.write(dataByte);
                } else {
                    break;//break loop
                }
            }
            fos.close();
        }
    }

    final FileUploadListenerFace<File> fulf;

    /**
     * Implement this as a set of listeners. Why it wasn't done now is that, a new object of listener should be
     * created per request and added to the listener pool(list or array whatever).
     */
    switch (Integer.parseInt(parameterMap.get("type"))) {
    case 1:
        fulf = CDNProfilePhoto.getProfilePhotoCDNLocal();
        break;
    case 2:
        fulf = CDNAlbumPrivateEvent.getAlbumPhotoCDNLocal();
        break;
    case 3:
        fulf = CDNAlbumTribe.getAlbumTribeCDNLocal();
        break;
    default:
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_SWITCH, "Unsupported Case", true);
    }
    if (tempFile == null) {
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION, "No File!", true);
    }

    return fulf.run(tempFile, parameterMap, userFileExtension, session);
}

From source file:com.liferay.faces.metal.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

    // Using the sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = getSessionId(externalContext);

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();//from   ww  w  .  j av a2 s .  co m
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

    // Parse the request parameters and save all uploaded files in a map.
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    servletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:com.liferay.faces.alloy.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

    // Using the sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = getSessionId(externalContext);

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();//from  w w w .  j a  va 2 s. c o  m
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

    // Parse the request parameters and save all uploaded files in a map.
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    servletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(externalContext, UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:fi.helsinki.lib.simplerest.CommunitiesResource.java

@Post
public Representation addCommunity(InputRepresentation rep) {
    Context c = null;//from   www  . jav  a 2  s  .  c  om
    Community community;
    try {
        c = getAuthenticatedContext();
        community = Community.find(c, this.communityId);
        if (community == null) {
            return errorNotFound(c, "Could not find the community.");
        }
    } catch (SQLException e) {
        return errorInternal(c, "SQLException");
    }

    String msg = null;
    String url = baseUrl();
    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        // Logo
        String bitstreamMimeType = null;
        byte[] logoBytes = null;

        // Community
        String name = null;
        String shortDescription = null;
        String introductoryText = null;
        String copyrightText = null;
        String sideBarText = null;

        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String key = fileItemStream.getFieldName();
                String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8");

                if (key.equals("name")) {
                    name = value;
                } else if (key.equals("short_description")) {
                    shortDescription = value;
                } else if (key.equals("introductory_text")) {
                    introductoryText = value;
                } else if (key.equals("copyright_text")) {
                    copyrightText = value;
                } else if (key.equals("side_bar_text")) {
                    sideBarText = value;
                } else {
                    return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } else {
                if (logoBytes != null) {
                    return error(c, "The community can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST);
                }

                // TODO: Refer to comments in....
                String fileName = fileItemStream.getName();
                if (fileName.length() == 0) {
                    continue;
                }
                int lastDot = fileName.lastIndexOf('.');
                if (lastDot != -1) {
                    String extension = fileName.substring(lastDot + 1);
                    extension = extension.toLowerCase();
                    if (extension.equals("jpg") || extension.equals("jpeg")) {
                        bitstreamMimeType = "image/jpeg";
                    } else if (extension.equals("png")) {
                        bitstreamMimeType = "image/png";
                    } else if (extension.equals("gif")) {
                        bitstreamMimeType = "image/gif";
                    }
                }
                if (bitstreamMimeType == null) {
                    String err = "The logo filename extension was not recognised.";
                    return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST);
                }

                InputStream inputStream = fileItemStream.openStream();
                logoBytes = IOUtils.toByteArray(inputStream);
            }
        }

        msg = "Community created.";
        Community subCommunity = community.createSubcommunity();
        subCommunity.setMetadata("name", name);
        subCommunity.setMetadata("short_description", shortDescription);
        subCommunity.setMetadata("introductory_text", introductoryText);
        subCommunity.setMetadata("copyright_text", copyrightText);
        subCommunity.setMetadata("side_bar_text", sideBarText);
        if (logoBytes != null) {
            ByteArrayInputStream byteStream;
            byteStream = new ByteArrayInputStream(logoBytes);
            subCommunity.setLogo(byteStream);
        }

        subCommunity.update();
        Bitstream logo = subCommunity.getLogo();
        if (logo != null) {
            BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType);
            logo.setFormat(bf);
            logo.update();
        }
        url += CommunityResource.relativeUrl(subCommunity.getID());
        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successCreated(msg, url);
}

From source file:fi.iki.elonen.SimpleWebServer.java

private Response getUploadMsgAndExec(IHTTPSession session) throws FileUploadException, IOException {
    uploader = new NanoFileUpload(new DiskFileItemFactory());
    files = new HashMap<String, List<FileItem>>();
    FileItemIterator iter = uploader.getItemIterator(session);
    String fileName = "", newFileName = "";
    try {/*  w  w  w  .j  a  va 2s . co  m*/
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            fileName = item.getName();
            newFileName = rootDirs.get(0) + "/".concat(fileName);
            FileItem fileItem = uploader.getFileItemFactory().createItem(item.getFieldName(),
                    item.getContentType(), item.isFormField(), newFileName);
            files.put(fileItem.getFieldName(), Arrays.asList(new FileItem[] { fileItem }));

            try {
                Streams.copy(item.openStream(), (new FileOutputStream(newFileName)), true);
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
            fileItem.setHeaders(item.getHeaders());
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return newFixedLengthResponse(
            "<html><body> \n File: " + fileName + " upload to " + newFileName + "! \n </body></html>\n");
}

From source file:com.webpagebytes.cms.controllers.FileController.java

public void upload(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    try {/*from  ww  w.j a  v a2  s  . com*/
        ServletFileUpload upload = new ServletFileUpload();
        upload.setHeaderEncoding("UTF-8");
        FileItemIterator iterator = upload.getItemIterator(request);
        WPBFile ownerFile = null;

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.isFormField() && item.getFieldName().equals("ownerExtKey")) {
                String ownerExtKey = Streams.asString(item.openStream());
                ownerFile = getDirectory(ownerExtKey, adminStorage);
            } else if (!item.isFormField() && item.getFieldName().equals("file")) {
                InputStream stream = item.openStream();
                WPBFile wbFile = null;

                String fileName = getFileNameFromLongName(item.getName());

                if (request.getAttribute("key") != null) {
                    // this is an upload as update for an existing file
                    Long key = Long.valueOf((String) request.getAttribute("key"));
                    wbFile = adminStorage.get(key, WPBFile.class);

                    ownerFile = getDirectory(wbFile.getOwnerExtKey(), adminStorage);

                    //old file need to be deleted from cloud
                    String oldFilePath = wbFile.getBlobKey();
                    if (oldFilePath != null && oldFilePath.length() > 0) {
                        // delete only if the blob key is set
                        WPBFilePath oldCloudFile = new WPBFilePath(PUBLIC_BUCKET, oldFilePath);
                        cloudFileStorage.deleteFile(oldCloudFile);
                    }
                } else {
                    // this is a new upload
                    wbFile = new WPBFile();
                    wbFile.setExternalKey(adminStorage.getUniqueId());
                }

                wbFile.setFileName(fileName);
                wbFile.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
                wbFile.setDirectoryFlag(0);
                addFileToDirectory(ownerFile, wbFile, stream);

            }
        }
        org.json.JSONObject returnJson = new org.json.JSONObject();
        returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null));
        httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null);
    } catch (Exception e) {
        Map<String, String> errors = new HashMap<String, String>();
        errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD);
        httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null),
                errors);
    }
}

From source file:com.google.sampling.experiential.server.EventServlet.java

private void processCsvUpload(HttpServletRequest req, HttpServletResponse resp) {
    PrintWriter out = null;/* w  ww  .  j a v  a 2  s  .c  om*/
    try {
        out = resp.getWriter();
    } catch (IOException e1) {
        log.log(Level.SEVERE, "Cannot get an output PrintWriter!");
    }
    try {
        boolean isDevInstance = isDevInstance(req);
        ServletFileUpload fileUploadTool = new ServletFileUpload();
        fileUploadTool.setSizeMax(50000);
        resp.setContentType("text/html;charset=UTF-8");

        FileItemIterator iterator = fileUploadTool.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = null;
            try {
                in = item.openStream();

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();

                    out.println("--------------");
                    out.println("fileName = " + fileName);
                    out.println("field name = " + fieldName);
                    out.println("contentType = " + contentType);

                    String fileContents = null;
                    fileContents = IOUtils.toString(in);
                    out.println("length: " + fileContents.length());
                    out.println(fileContents);
                    saveCSV(fileContents, isDevInstance);
                }
            } catch (ParseException e) {
                log.info("Parse Exception: " + e.getMessage());
                out.println("Could not parse your csv upload: " + e.getMessage());
            } finally {
                in.close();
            }
        }
    } catch (SizeLimitExceededException e) {
        log.info("SizeLimitExceededException: " + e.getMessage());
        out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                + e.getActualSize() + ")");
        return;
    } catch (IOException e) {
        log.severe("IOException: " + e.getMessage());
        out.println("Error in receiving file.");
    } catch (FileUploadException e) {
        log.severe("FileUploadException: " + e.getMessage());
        out.println("Error in receiving file.");
    }
}

From source file:fi.helsinki.lib.simplerest.CollectionsResource.java

@Post
public Representation addCollection(InputRepresentation rep) {
    Context c = null;/*from  w  w  w  .  j a va 2s  .c  o  m*/
    Community community;
    try {
        c = getAuthenticatedContext();
        community = Community.find(c, this.communityId);
        if (community == null) {
            return errorNotFound(c, "Could not find the community.");
        }
    } catch (SQLException e) {
        return errorInternal(c, "SQLException");
    }

    String msg = null;
    String url = baseUrl();
    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        // Logo
        String bitstreamMimeType = null;
        byte[] logoBytes = null;

        // Collection
        String name = null;
        String shortDescription = null;
        String introductoryText = null;
        String copyrightText = null;
        String sideBarText = null;
        String provenanceDescription = null;
        String license = null;

        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String key = fileItemStream.getFieldName();
                String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8");

                if (key.equals("name")) {
                    name = value;
                } else if (key.equals("short_description")) {
                    shortDescription = value;
                } else if (key.equals("introductory_text")) {
                    introductoryText = value;
                } else if (key.equals("copyright_text")) {
                    copyrightText = value;
                } else if (key.equals("side_bar_text")) {
                    sideBarText = value;
                } else if (key.equals("provenance_description")) {
                    provenanceDescription = value;
                } else if (key.equals("license")) {
                    license = value;
                } else {
                    return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } else {
                if (logoBytes != null) {
                    return error(c, "The collection can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST);
                }

                // TODO: Refer to comments in....
                String fileName = fileItemStream.getName();
                if (fileName.length() == 0) {
                    continue;
                }
                int lastDot = fileName.lastIndexOf('.');
                if (lastDot != -1) {
                    String extension = fileName.substring(lastDot + 1);
                    extension = extension.toLowerCase();
                    if (extension.equals("jpg") || extension.equals("jpeg")) {
                        bitstreamMimeType = "image/jpeg";
                    } else if (extension.equals("png")) {
                        bitstreamMimeType = "image/png";
                    } else if (extension.equals("gif")) {
                        bitstreamMimeType = "image/gif";
                    }
                }
                if (bitstreamMimeType == null) {
                    String err = "The logo filename extension was not recognised.";
                    return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST);
                }

                InputStream inputStream = fileItemStream.openStream();
                logoBytes = IOUtils.toByteArray(inputStream);
            }
        }

        Collection collection = community.createCollection();
        collection.setMetadata("name", name);
        collection.setMetadata("short_description", shortDescription);
        collection.setMetadata("introductory_text", introductoryText);
        collection.setMetadata("copyright_text", copyrightText);
        collection.setMetadata("side_bar_text", sideBarText);
        collection.setMetadata("provenance_description", provenanceDescription);
        collection.setMetadata("license", license);
        if (logoBytes != null) {
            ByteArrayInputStream byteStream;
            byteStream = new ByteArrayInputStream(logoBytes);
            collection.setLogo(byteStream);
        }

        collection.update();
        Bitstream logo = collection.getLogo();
        if (logo != null) {
            BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType);
            logo.setFormat(bf);
            logo.update();
        }
        url += CollectionResource.relativeUrl(collection.getID());
        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successCreated("Collection created.", url);
}