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

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

Introduction

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

Prototype

boolean isFormField();

Source Link

Document

Determines whether or not a FileItem instance represents a simple form field.

Usage

From source file:edu.isi.wings.portal.servlets.HandleUpload.java

/**
 * Handle an HTTP POST request from Plupload.
 *///  w  w w.j av a2  s .c o m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    Config config = new Config(request);
    if (!config.checkDomain(request, response))
        return;

    Domain dom = config.getDomain();

    String name = null;
    String id = null;
    String storageDir = dom.getDomainDirectory() + "/";
    int chunk = 0;
    int chunks = 0;
    boolean isComponent = false;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter;
        try {
            iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                try {
                    InputStream input = item.openStream();
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String value = Streams.asString(input);
                        if ("name".equals(fieldName))
                            name = value.replaceAll("[^\\w\\.\\-_]+", "_");
                        else if ("id".equals(fieldName))
                            id = value;
                        else if ("type".equals(fieldName)) {
                            if ("data".equals(value))
                                storageDir += dom.getDataLibrary().getStorageDirectory();
                            else if ("component".equals(value)) {
                                storageDir += dom.getConcreteComponentLibrary().getStorageDirectory();
                                isComponent = true;
                            } else {
                                storageDir = System.getProperty("java.io.tmpdir");
                            }
                        } else if ("chunk".equals(fieldName))
                            chunk = Integer.parseInt(value);
                        else if ("chunks".equals(fieldName))
                            chunks = Integer.parseInt(value);
                    } else if (name != null) {
                        File storageDirFile = new File(storageDir);
                        if (!storageDirFile.exists())
                            storageDirFile.mkdirs();
                        File uploadFile = new File(storageDirFile.getPath() + "/" + name + ".part");
                        saveUploadFile(input, uploadFile, chunk);
                    }
                } catch (Exception e) {
                    this.printError(out, e.getMessage());
                    e.printStackTrace();
                }
            }
        } catch (FileUploadException e1) {
            this.printError(out, e1.getMessage());
            e1.printStackTrace();
        }
    } else {
        this.printError(out, "Not multipart data");
    }

    if (chunks == 0 || chunk == chunks - 1) {
        // Done upload
        File partUpload = new File(storageDir + File.separator + name + ".part");
        File finalUpload = new File(storageDir + File.separator + name);
        partUpload.renameTo(finalUpload);

        String mime = new Tika().detect(finalUpload);
        if (mime.equals("application/x-sh") || mime.startsWith("text/"))
            FileUtils.writeLines(finalUpload, FileUtils.readLines(finalUpload));

        // Check if this is a zip file and unzip if needed
        String location = finalUpload.getAbsolutePath();
        if (isComponent && mime.equals("application/zip")) {
            String dirname = new URI(id).getFragment();
            location = StorageHandler.unzipFile(finalUpload, dirname, storageDir);
            finalUpload.delete();
        }
        this.printOk(out, location);
    }
}

From source file:com.newatlanta.appengine.servlet.GaeVfsServlet.java

/**
 * Writes the uploaded file to the GAE virtual file system (GaeVFS). Copied from:
 * //from w  w  w.  ja  va 2 s .c om
 *      http://code.google.com/appengine/kb/java.html#fileforms
 * 
 * The "path" form parameter specifies a <a href="http://code.google.com/p/gaevfs/wiki/CombinedLocalOption"
 * target="_blank">GaeVFS path</a>. All directories within the path hierarchy
 * are created (if they don't already exist) when the file is saved.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        res.sendError(SC_BAD_REQUEST, "form enctype not multipart/form-data");
    }
    try {
        String path = "/";
        int blockSize = 0;
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(req);

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase("path")) {
                    path = asString(item.openStream());
                    if (!path.endsWith("/")) {
                        path = path + "/";
                    }
                } else if (item.getFieldName().equalsIgnoreCase("blocksize")) {
                    String s = asString(item.openStream());
                    if (s.length() > 0) {
                        blockSize = Integer.parseInt(s);
                    }
                }
            } else {
                Path filePath = Paths.get(path + item.getName());
                Path parent = filePath.getParent();
                if (parent.notExists()) {
                    createDirectories(parent);
                }
                if (blockSize > 0) {
                    filePath.createFile(withBlockSize(blockSize));
                } else {
                    filePath.createFile();
                }
                // IOUtils.copy() buffers the InputStream internally
                OutputStream out = new BufferedOutputStream(filePath.newOutputStream(), BUFF_SIZE);
                copy(item.openStream(), out);
                out.close();
            }
        }

        // redirect to the configured response, or to this servlet for a
        // directory listing
        res.sendRedirect(uploadRedirect != null ? uploadRedirect : path);

    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
}

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

/**
 * Receive an upload book assest//from   w  w  w .ja v a 2 s .c om
 * 
 * @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:com.twosigma.beaker.core.module.elfinder.ConnectorController.java

private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request))
        return request;

    final Map<String, String> requestParams = new HashMap<String, String>();
    List<FileItemStream> listFiles = new ArrayList<FileItemStream>();

    // Parse the request
    ServletFileUpload sfu = new ServletFileUpload();
    String characterEncoding = request.getCharacterEncoding();
    if (characterEncoding == null) {
        characterEncoding = "UTF-8";
    }/*from  w w  w. j a  v  a 2 s  . c om*/
    sfu.setHeaderEncoding(characterEncoding);
    FileItemIterator iter = sfu.getItemIterator(request);

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream, characterEncoding));
        } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(stream, os);
                final byte[] bs = os.toByteArray();
                stream.close();

                listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                        new Class[] { FileItemStream.class }, new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if ("openStream".equals(method.getName())) {
                                    return new ByteArrayInputStream(bs);
                                }

                                return method.invoke(item, args);
                            }
                        }));
            }
        }
    }

    request.setAttribute(FileItemStream.class.getName(), listFiles);

    Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
                    // we replace getParameter() and getParameterValues()
                    // methods
                    if ("getParameter".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];
                        return requestParams.get(paramName);
                    }

                    if ("getParameterValues".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];

                        // normalize name 'key[]' to 'key'
                        if (paramName.endsWith("[]"))
                            paramName = paramName.substring(0, paramName.length() - 2);

                        if (requestParams.containsKey(paramName))
                            return new String[] { requestParams.get(paramName) };

                        // if contains key[1], key[2]...
                        int i = 0;
                        List<String> paramValues = new ArrayList<String>();
                        while (true) {
                            String name2 = String.format("%s[%d]", paramName, i++);
                            if (requestParams.containsKey(name2)) {
                                paramValues.add(requestParams.get(name2));
                            } else {
                                break;
                            }
                        }

                        return paramValues.isEmpty() ? new String[0]
                                : paramValues.toArray(new String[paramValues.size()]);
                    }

                    return arg1.invoke(request, arg2);
                }
            });
    return (HttpServletRequest) proxyInstance;
}

From source file:com.chinarewards.gwt.license.util.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // text/html IE??
    response.setContentType("text/plain;charset=utf-8");

    StringBuffer responseMessage = new StringBuffer("<?xml version=\"1.0\" encoding=\"GB2312\"?>");
    responseMessage.append("<root>");

    StringBuffer errorMsg = new StringBuffer(responseMessage).append("<result>").append("FAILED")
            .append("</result>");

    String info = "";
    ServletFileUpload upload = new ServletFileUpload();

    FileItemIterator iter = null;// w  w  w  .ja  v a2s. c  o  m
    try {
        iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                info = "Form field " + name + " with value " + Streams.asString(stream) + " detected.";
                responseMessage = new StringBuffer(responseMessage).append(errorMsg).append("<info>")
                        .append(info).append("</info>");
                finishPrintResponseMsg(response, responseMessage);
                return;
            } else {
                BufferedInputStream inputStream = new BufferedInputStream(stream);// ?

                String uploadPath = getUploadPath(request, "upload");
                if (uploadPath != null) {
                    String fileName = getOutputFileName(item);
                    String outputFilePath = getOutputFilePath(uploadPath, fileName);

                    int widthdist = 72;
                    int heightdist = 72;

                    widthdist = 200;
                    heightdist = 200;

                    BufferedOutputStream outputStream = new BufferedOutputStream(
                            new FileOutputStream(new File(outputFilePath)));// ?
                    Streams.copy(inputStream, outputStream, true); //
                    //                   stream.close();

                    reduceImg(inputStream, outputFilePath, outputFilePath, widthdist, heightdist, 0);

                    stream.close();

                    responseMessage.append("<result>").append("SUCCESS").append("</result>");
                    responseMessage.append("<info>");
                    responseMessage.append(fileName);
                    responseMessage.append(info).append("</info>");
                } else {
                    responseMessage = errorMsg.append("<info>").append("")
                            .append("</info>");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        responseMessage = errorMsg.append("<info>").append(":" + e.getMessage())
                .append("</info>");
    }
    finishPrintResponseMsg(response, responseMessage);
}

From source file:com.google.phonenumbers.PhoneNumberParserServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String phoneNumber = null;// ww w .  j  a va2s  . c  o  m
    String defaultCountry = null;
    String languageCode = "en"; // Default languageCode to English if nothing is entered.
    String regionCode = "";
    String fileContents = null;
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(50000);
    try {
        FileItemIterator iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = item.openStream();
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName.equals("phoneNumber")) {
                    phoneNumber = Streams.asString(in, "UTF-8");
                } else if (fieldName.equals("defaultCountry")) {
                    defaultCountry = Streams.asString(in).toUpperCase();
                } else if (fieldName.equals("languageCode")) {
                    String languageEntered = Streams.asString(in).toLowerCase();
                    if (languageEntered.length() > 0) {
                        languageCode = languageEntered;
                    }
                } else if (fieldName.equals("regionCode")) {
                    regionCode = Streams.asString(in).toUpperCase();
                }
            } else {
                try {
                    fileContents = IOUtils.toString(in);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

    StringBuilder output;
    if (fileContents.length() == 0) {
        output = getOutputForSingleNumber(phoneNumber, defaultCountry, languageCode, regionCode);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().println("<html><head>");
        resp.getWriter()
                .println("<link type=\"text/css\" rel=\"stylesheet\" href=\"/stylesheets/main.css\" />");
        resp.getWriter().println("</head>");
        resp.getWriter().println("<body>");
        resp.getWriter().println("Phone Number entered: " + phoneNumber + "<br>");
        resp.getWriter().println("defaultCountry entered: " + defaultCountry + "<br>");
        resp.getWriter().println("Language entered: " + languageCode
                + (regionCode.length() == 0 ? "" : " (" + regionCode + ")" + "<br>"));
    } else {
        output = getOutputForFile(defaultCountry, fileContents);
        resp.setContentType("text/html");
    }
    resp.getWriter().println(output);
    resp.getWriter().println("</body></html>");
}

From source file:com.sifiso.dvs.util.PhotoUtil.java

public ResponseDTO downloadPhotos(HttpServletRequest request, PlatformUtil platformUtil)
        throws FileUploadException {
    logger.log(Level.INFO, "######### starting PHOTO DOWNLOAD process\n\n");
    ResponseDTO resp = new ResponseDTO();
    InputStream stream = null;//from  ww  w  .java2s  .c o m
    File rootDir;
    try {
        rootDir = dvsProperties.getImageDir();
        logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath());
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Properties file problem", ex);
        resp.setMessage("Server file unavailable. Please try later");
        resp.setStatusCode(114);

        return resp;
    }

    PhotoUploadDTO dto = null;
    Gson gson = new Gson();
    File doctorFileDir = null, surgeryDir = null;
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            stream = item.openStream();
            if (item.isFormField()) {
                if (name.equalsIgnoreCase("JSON")) {
                    String json = Streams.asString(stream);
                    if (json != null) {
                        logger.log(Level.INFO, "picture with associated json: {0}", json);
                        dto = gson.fromJson(json, PhotoUploadDTO.class);
                        if (dto != null) {
                            surgeryDir = createSurgeryFileDirectory(rootDir, surgeryDir, dto.getSurgeryID());
                            if (dto.getDoctorID() > 0) {
                                doctorFileDir = createDoctorDirectory(surgeryDir, doctorFileDir,
                                        dto.getDoctorID());
                            }

                        }
                    } else {
                        logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL..");
                    }
                }
            } else {
                File imageFile = null;
                if (dto == null) {
                    continue;
                }
                DateTime dt = new DateTime();
                String fileName = "";
                if (dto.isIsFullPicture()) {
                    fileName = "f" + dt.getMillis() + ".jpg";
                } else {
                    fileName = "t" + dt.getMillis() + ".jpg";
                }
                if (dto.getPatientfileID() != null) {
                    if (dto.isIsFullPicture()) {
                        fileName = "f" + dto.getPatientfileID() + ".jpg";
                    } else {
                        fileName = "t" + dto.getPatientfileID() + ".jpg";
                    }
                }

                //
                switch (dto.getPictureType()) {
                case PhotoUploadDTO.FILES_DOCTOR:
                    imageFile = new File(doctorFileDir, fileName);
                    break;
                case PhotoUploadDTO.FILES_SURGERY:
                    imageFile = new File(surgeryDir, fileName);
                }

                writeFile(stream, imageFile);
                resp.setStatusCode(0);
                resp.setMessage("Photo downloaded from mobile app ");
                //add database
                System.out.println("filepath: " + imageFile.getAbsolutePath());
                //create uri
                /*int index = imageFile.getAbsolutePath().indexOf("monitor_images");
                 if (index > -1) {
                 String uri = imageFile.getAbsolutePath().substring(index);
                 System.out.println("uri: " + uri);
                 dto.setUri(uri);
                 }
                 dto.setDateUploaded(new Date());
                 if (dto.isIsFullPicture()) {
                 dto.setThumbFlag(null);
                 } else {
                 dto.setThumbFlag(1);
                 }
                 dataUtil.addPhotoUpload(dto);*/

            }
        }

    } catch (FileUploadException | IOException | JsonSyntaxException ex) {
        logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex);
        throw new FileUploadException();
    }

    return resp;
}

From source file:com.fullmetalgalaxy.server.AdminServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_resp)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    Map<String, String> params = new HashMap<String, String>();
    ModelFmpInit modelInit = null;/*from   ww w. j a v  a  2  s  . com*/

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream(), "UTF-8"));
            } else if (item.getFieldName().equalsIgnoreCase("gamefile")) {
                ObjectInputStream in = new ObjectInputStream(item.openStream());
                modelInit = ModelFmpInit.class.cast(in.readObject());
                in.close();
            }
        }
    } catch (FileUploadException e) {
        log.error(e);
    } catch (ClassNotFoundException e2) {
        log.error(e2);
    }

    // import game from file
    if (modelInit != null) {
        // set transient to avoid override data
        modelInit.getGame().setTrancient();

        // search all accounts in database to correct ID
        for (EbRegistration registration : modelInit.getGame().getSetRegistration()) {
            if (registration.haveAccount()) {
                EbAccount account = FmgDataStore.dao().find(EbAccount.class, registration.getAccount().getId());
                if (account == null) {
                    // corresponding account from this player doesn't exist in database
                    try {
                        // try to find corresponding pseudo
                        account = FmgDataStore.dao().query(EbAccount.class).filter("m_compactPseudo ==",
                                ServerUtil.compactTag(registration.getAccount().getPseudo())).get();
                    } catch (Exception e) {
                    }
                }
                registration.setAccount(account);
            }
        }

        // then save game
        FmgDataStore dataStore = new FmgDataStore(false);
        dataStore.put(modelInit.getGame());
        dataStore.close();

    }

}

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

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

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

@Post
public Representation addCommunity(InputRepresentation rep) {
    Context c = null;//w  w w  . j  av  a  2 s .com
    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()));
}