Example usage for org.apache.commons.fileupload FileItemStream getFieldName

List of usage examples for org.apache.commons.fileupload FileItemStream getFieldName

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream getFieldName.

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:kg12.Ex12_2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w  w . ja v  a2 s .  com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet Ex12_2</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>???</h1>");

        // multipart/form-data ??
        if (ServletFileUpload.isMultipartContent(request)) {
            out.println("???<br>");
        } else {
            out.println("?????<br>");
            out.close();
            return;
        }

        // ServletFileUpload??
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);

        // ???
        int fileSizeMax = 1024000;
        factory.setSizeThreshold(1024);
        sfu.setSizeMax(fileSizeMax);
        sfu.setHeaderEncoding("UTF-8");

        // ?
        String format = "%s:%s<br>%n";

        // ???????
        FileItemIterator fileIt = sfu.getItemIterator(request);

        while (fileIt.hasNext()) {
            FileItemStream item = fileIt.next();

            if (item.isFormField()) {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getFieldName());
                InputStream is = item.openStream();

                // ? byte ??
                byte[] b = new byte[255];

                // byte? b ????
                is.read(b, 0, b.length);

                // byte? b ? "UTF-8" ??String??? result ?
                String result = new String(b, "UTF-8");
                out.printf(format, "", result);
            } else {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getName());
                InputStream is = item.openStream();

                String fileName = item.getName();
                int len = 0;
                byte[] buffer = new byte[fileSizeMax];

                FileOutputStream fos = new FileOutputStream(
                        "D:\\NetBeansProjects\\ap2_www\\web\\kg12\\" + fileName);
                try {
                    while ((len = is.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                } finally {
                    fos.close();
                }

            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } catch (Exception e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } finally {
        out.close();
    }
}

From source file:com.pronoiahealth.olhie.server.rest.BookAssetUploadServiceImpl.java

/**
 * Receive an upload book assest/*  www.j  a v a  2  s. c o m*/
 * 
 * @see com.pronoiahealth.olhie.server.rest.BookAssetUploadService#process2(javax.servlet.http.HttpServletRequest)
 */
@Override
@POST
@Path("/upload2")
@Produces("text/html")
@SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR })
public String process2(@Context HttpServletRequest req)
        throws ServletException, IOException, FileUploadException {
    try {
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart == true) {

            // FileItemFactory fileItemFactory = new FileItemFactory();
            String description = null;
            String descriptionDetail = null;
            String hoursOfWorkStr = null;
            String bookId = null;
            String action = null;
            String dataType = null;
            String contentType = null;
            //String data = null;
            byte[] bytes = null;
            String fileName = null;
            long size = 0;
            ServletFileUpload fileUpload = new ServletFileUpload();
            fileUpload.setSizeMax(FILE_SIZE_LIMIT);
            FileItemIterator iter = fileUpload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // description
                    if (item.getFieldName().equals("description")) {
                        description = Streams.asString(stream);
                    }

                    // detail
                    if (item.getFieldName().equals("descriptionDetail")) {
                        descriptionDetail = Streams.asString(stream);
                    }

                    // Work hours
                    if (item.getFieldName().equals("hoursOfWork")) {
                        hoursOfWorkStr = Streams.asString(stream);
                    }

                    // BookId
                    if (item.getFieldName().equals("bookId")) {
                        bookId = Streams.asString(stream);
                    }

                    // action
                    if (item.getFieldName().equals("action")) {
                        action = Streams.asString(stream);
                    }

                    // datatype
                    if (item.getFieldName().equals("dataType")) {
                        dataType = Streams.asString(stream);
                    }

                } else {
                    if (item != null) {
                        contentType = item.getContentType();
                        fileName = item.getName();
                        item.openStream();
                        InputStream in = item.openStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        IOUtils.copy(in, bos);
                        bytes = bos.toByteArray();
                        size = bytes.length;
                    }
                }
            }

            // convert the hoursOfWork
            int hoursOfWork = 0;
            if (hoursOfWorkStr != null) {
                try {
                    hoursOfWork = Integer.parseInt(hoursOfWorkStr);
                } catch (Exception e) {
                    log.log(Level.WARNING, "Could not conver " + hoursOfWorkStr
                            + " to an int in BookAssetUploadServiceImpl. Converting to 0.");
                    hoursOfWork = 0;
                }
            }

            // Verify that the session user is the author or co-author of
            // the book. They would be the only ones who could add to the
            // book.
            String userId = userToken.getUserId();
            boolean isAuthor = bookDAO.isUserAuthorOrCoauthorOfBook(userId, bookId);
            if (isAuthor == false) {
                throw new Exception("The user " + userId + " is not the author or co-author of the book.");
            }

            // Add to the database
            bookDAO.addUpdateBookassetBytes(description, descriptionDetail, bookId, contentType,
                    BookAssetDataType.valueOf(dataType).toString(), bytes, action, fileName, null, null, size,
                    hoursOfWork, userId);

            // Tell Solr about the update
            queueBookEvent.fire(new QueueBookEvent(bookId, userId));
        }
        return "OK";
    } catch (Exception e) {
        log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
        // return "ERROR:\n" + e.getMessage();

        if (e instanceof FileUploadException) {
            throw (FileUploadException) e;
        } else {
            throw new FileUploadException(e.getMessage());
        }
    }
}

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);
        }//  w w w .jav 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;
    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:fi.helsinki.lib.simplerest.RootCommunitiesResource.java

@Post
public Representation addCommunity(InputRepresentation rep) {
    Context c = null;/*from  ww w  .j a v a  2 s.c o m*/
    Community community;
    try {
        c = getAuthenticatedContext();
        community = Community.create(null, c);

        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        String name = null;
        String shortDescription = null;
        String introductoryText = null;
        String copyrightText = null;
        String sideBarText = null;
        Bitstream bitstream = null;
        String bitstreamMimeType = 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 (bitstream != null) {
                    return error(c, "The community can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST);
                }

                // I did not manage to use FormatIdentifier.guessFormat
                // here, so let's do it by ourselves... I would prefer to
                // use the actual file content and not its name, but let's
                // keep the code simple...
                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);
                }

                bitstream = community.setLogo(fileItemStream.openStream());
                // We don't set the format of the logo (bitstream) here,
                // it's done in the code below...
            }
        }

        community.setMetadata("name", name);
        community.setMetadata("short_description", shortDescription);
        community.setMetadata("introductory_text", introductoryText);
        community.setMetadata("copyright_text", copyrightText);
        community.setMetadata("side_bar_text", sideBarText);

        community.update();

        // Set the format (jpeg, png, or gif) of logo:
        Bitstream logo = community.getLogo();
        if (logo != null) {
            BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType);
            logo.setFormat(bf);
            logo.update();
        }

        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successCreated("Community created.", baseUrl() + CommunityResource.relativeUrl(community.getID()));
}

From source file:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java

private void parseReq(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {

    try {/* www . j  a  va 2  s  . c  o  m*/

        MF mf = MF.getFactory();

        req.setCharacterEncoding("UTF-8");

        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(req);

        HashMap<String, String> map = new HashMap<String, String>();

        while (iterator.hasNext()) {

            FileItemStream item = iterator.next();

            InputStream stream = item.openStream();

            if (item.isFormField()) {

                String field = item.getFieldName();

                String value = Streams.asString(stream);

                map.put(field, value);

                stream.close();

            } else {

                String filename = item.getName();

                String[] extension = filename.split("\\.");

                String mail = map.get("mail");

                if (mail != null) {

                    filename = mail + "_" + String.valueOf(filename.hashCode()) + "."
                            + extension[extension.length - 1];

                } else {

                    filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1];

                }

                map.put("filename", filename);

                byte[] buffer = IOUtils.toByteArray(stream);

                mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer,

                        filename);

                stream.close();

            }

        }

        String email = map.get("mail");

        String firstName = map.get("firstName");

        String lastName = map.get("lastName");

        String dayS = map.get("day");

        String monthS = map.get("month");

        String yearS = map.get("year");

        String password = map.get("password");

        String filename = map.get("filename");

        String date = yearS + "-" + monthS + "-" + dayS;

        char gender = map.get("gender").charAt(0);

        RequestDispatcher disp;

        Connection c = mf.getSQLService().getConnection();

        String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName
                + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')";

        Statement statement = c.createStatement();

        statement.executeUpdate(stm);

        statement.close();

        c.close();

        req.getSession(true).setAttribute("actualUser", email);

        req.getSession(true).setAttribute("edit", "false");

        disp = req.getRequestDispatcher("SelectTopic.jsp");

        disp.forward(req, response);

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();

    } catch (SQLException e) {

        e.printStackTrace();

    } catch (FileUploadException e) {

        e.printStackTrace();

    }

}

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

@Post
public Representation addItem(InputRepresentation rep)
        throws AuthorizeException, SQLException, IdentifierException {
    Collection collection = null;
    Context addItemContext = null;
    try {/*from   w w  w .j a va2  s.  c o m*/
        //Get Context and make sure the user has the rights to add items.
        addItemContext = getAuthenticatedContext();
        collection = Collection.find(addItemContext, this.collectionId);
        if (collection == null) {
            addItemContext.abort();
            return errorNotFound(addItemContext, "Could not find the collection.");
        }
    } catch (SQLException e) {
        log.log(Priority.ERROR, e);
        return errorInternal(addItemContext, "SQLException");
    } catch (NullPointerException e) {
        log.log(Priority.ERROR, e);
        return errorInternal(addItemContext, "NullPointerException");
    }
    String title = null;
    String lang = null;

    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        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("title")) {
                    title = value;
                } else if (key.equals("lang")) {
                    lang = value;
                } else if (key.equals("in_archive")) {
                    ;
                } else if (key.equals("withdrawn")) {
                    ;
                } else {
                    return error(addItemContext, "Unexpected attribute: " + key,
                            Status.CLIENT_ERROR_BAD_REQUEST);
                }
            }
        }
    } catch (FileUploadException e) {
        return errorInternal(addItemContext, e.toString());
    } catch (NullPointerException e) {
        log.log(Priority.INFO, e);
        return errorInternal(context, e.toString());
    } catch (IOException e) {
        return errorInternal(context, e.toString());
    }

    if (title == null) {
        return error(addItemContext, "There was no title given.", Status.CLIENT_ERROR_BAD_REQUEST);
    }

    Item item = null;
    try {
        WorkspaceItem wsi = WorkspaceItem.create(addItemContext, collection, false);
        item = InstallItem.installItem(addItemContext, wsi);
        item.addMetadata("dc", "title", null, lang, title);
        item.update();
    } catch (AuthorizeException ae) {
        return error(addItemContext, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (SQLException e) {
        log.log(Priority.FATAL, e, e);
        return errorInternal(addItemContext, e.toString());
    } catch (IOException e) {
        log.log(Priority.FATAL, e, e);
        return errorInternal(addItemContext, e.toString());
    } finally {
        if (addItemContext != null) {
            addItemContext.complete();
        }
    }

    return successCreated("Created a new item.", baseUrl() + ItemResource.relativeUrl(item.getID()));
}

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

@Post
public Representation addBitstream(InputRepresentation rep) {
    Context c = null;//from   ww  w.  j  ava2 s  .c  o m
    Bundle bundle = null;
    Bitstream bitstream = null;
    try {
        c = getAuthenticatedContext();
        bundle = Bundle.find(c, this.bundleId);
        if (bundle == null) {
            return errorNotFound(c, "Could not find the bundle.");
        }

        Item[] items = bundle.getItems();

        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        String description = 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("description")) {
                    description = value;
                } else {
                    return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } else {
                if (bitstream != null) {
                    return error(c, "Only one file can added in one request.", Status.CLIENT_ERROR_BAD_REQUEST);
                }
                String name = fileItemStream.getName();
                bitstream = bundle.createBitstream(fileItemStream.openStream());
                bitstream.setName(name);
                bitstream.setSource(name);
                BitstreamFormat bf = FormatIdentifier.guessFormat(c, bitstream);
                bitstream.setFormat(bf);
            }
        }

        if (bitstream == null) {
            return error(c, "Request does not contain file(?)", Status.CLIENT_ERROR_BAD_REQUEST);
        }
        if (description != null) {
            bitstream.setDescription(description);
        }
        bitstream.update();
        items[0].update(); // This updates at least the
                           // sequence ID of the bitstream.

        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successCreated("Bitstream created.", baseUrl() + BitstreamResource.relativeUrl(bitstream.getID()));
}

From source file:com.manydesigns.portofino.stripes.StreamingCommonsMultipartWrapper.java

/**
 * Pseudo-constructor that allows the class to perform any initialization necessary.
 *
 * @param request     an HttpServletRequest that has a content-type of multipart.
 * @param tempDir a File representing the temporary directory that can be used to store
 *        file parts as they are uploaded if this is desirable
 * @param maxPostSize the size in bytes beyond which the request should not be read, and a
 *                    FileUploadLimitExceeded exception should be thrown
 * @throws IOException if a problem occurs processing the request of storing temporary
 *                    files/*from w  ww  .j  a v a 2 s .co m*/
 * @throws FileUploadLimitExceededException if the POST content is longer than the
 *                     maxPostSize supplied.
 */
@SuppressWarnings("unchecked")
public void build(HttpServletRequest request, File tempDir, long maxPostSize)
        throws IOException, FileUploadLimitExceededException {
    try {
        this.charset = request.getCharacterEncoding();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxPostSize);
        FileItemIterator iterator = upload.getItemIterator(request);

        Map<String, List<String>> params = new HashMap<String, List<String>>();

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();

            // If it's a form field, add the string value to the list
            if (item.isFormField()) {
                List<String> values = params.get(item.getFieldName());
                if (values == null) {
                    values = new ArrayList<String>();
                    params.put(item.getFieldName(), values);
                }
                values.add(charset == null ? IOUtils.toString(stream) : IOUtils.toString(stream, charset));
            }
            // Else store the file param
            else {
                TempFile tempFile = TempFileService.getInstance().newTempFile(item.getContentType(),
                        item.getName());
                int size = IOUtils.copy(stream, tempFile.getOutputStream());
                FileItem fileItem = new FileItem(item.getName(), item.getContentType(), tempFile, size);
                files.put(item.getFieldName(), fileItem);
            }
        }

        // Now convert them down into the usual map of String->String[]
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            List<String> values = entry.getValue();
            this.parameters.put(entry.getKey(), values.toArray(new String[values.size()]));
        }
    } catch (FileUploadBase.SizeLimitExceededException slee) {
        throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize());
    } catch (FileUploadException fue) {
        IOException ioe = new IOException("Could not parse and cache file upload data.");
        ioe.initCause(fue);
        throw ioe;
    }

}

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

@Post
public Representation addCommunity(InputRepresentation rep) {
    Context c = null;/* ww w.ja  va2 s .  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;

        // 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.helsinki.lib.simplerest.CollectionsResource.java

@Post
public Representation addCollection(InputRepresentation rep) {
    Context c = null;/*from ww w  .j  a  v a 2  s.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);
}