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

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

Introduction

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

Prototype

InputStream openStream() throws IOException;

Source Link

Document

Creates an InputStream , which allows to read the items contents.

Usage

From source file:de.eorganization.hoopla.server.servlets.TemplateImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    DecisionTemplate newDecisionTemplate = new DecisionTemplate();
    DecisionTemplate decisionTemplate = null;
    try {/*from  w  ww. j  ava2  s. c  om*/

        ServletFileUpload upload = new ServletFileUpload();
        resp.setContentType("text/plain");

        FileItemIterator itemIterator = upload.getItemIterator(req);
        while (itemIterator.hasNext()) {
            FileItemStream item = itemIterator.next();
            if (item.isFormField() && "substituteTemplateId".equals(item.getFieldName())) {
                log.warning("Got a form field: " + item.getFieldName());

                String itemContent = IOUtils.toString(item.openStream());
                try {
                    decisionTemplate = new HooplaServiceImpl()
                            .getDecisionTemplate(new Long(itemContent).longValue());
                    new HooplaServiceImpl().deleteDecisionTemplate(decisionTemplate);
                } catch (Exception e) {
                    log.log(Level.WARNING, e.getLocalizedMessage(), e);
                }
                if (decisionTemplate == null)
                    newDecisionTemplate.setKeyId(new Long(itemContent).longValue());
                else
                    newDecisionTemplate.setKeyId(decisionTemplate.getKeyId());
            } else {
                InputStream stream = item.openStream();

                log.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream);

                // doc.getDocumentElement().normalize();

                Element decisionElement = doc.getDocumentElement();
                String rootName = decisionElement.getNodeName();
                if (rootName.equals("decision")) {
                    isDecisionTemplate = false;
                } else if (rootName.equals("decisionTemplate")) {
                    isDecisionTemplate = true;
                } else {
                    log.warning("This XML Document has a wrong RootElement: " + rootName
                            + ". It should be <decision> or <decisionTemplate>.");
                }

                NodeList decisionNodes = decisionElement.getChildNodes();
                for (int i = 0; i < decisionNodes.getLength(); i++) {
                    Node node = decisionNodes.item(i);

                    if (node instanceof Element) {
                        Element child = (Element) node;
                        if (child.getNodeName().equals("name") && !child.getTextContent().equals("")) {
                            newDecisionTemplate.setName(child.getTextContent());
                            log.info("Parsed decision name: " + newDecisionTemplate.getName());
                        }
                        if (child.getNodeName().equals("description") && !child.getTextContent().equals("")) {
                            newDecisionTemplate.setDescription(child.getTextContent());
                            log.info("Parsed decision description: " + newDecisionTemplate.getDescription());
                        }
                        if (isDecisionTemplate && child.getNodeName().equals("templateName")) {
                            newDecisionTemplate.setTemplateName(child.getTextContent());
                            log.info("Parsed decision TemplateName: " + newDecisionTemplate.getTemplateName());
                        }
                        if (child.getNodeName().equals("alternatives")) {
                            parseAlternatives(child.getChildNodes(), newDecisionTemplate);
                        }
                        if (child.getNodeName().equals("goals")) {
                            parseGoals(child.getChildNodes(), newDecisionTemplate);
                        }
                        if (child.getNodeName().equals("importanceGoals")) {
                            parseGoalImportances(child.getChildNodes(), newDecisionTemplate);
                        }
                    }
                }

                log.info("Fully parsed XML Upload: " + newDecisionTemplate.toString());

            }
        }

    } catch (Exception ex) {
        log.log(Level.WARNING, ex.getLocalizedMessage(), ex);
        resp.sendError(400);
        return;
    }

    try {
        new HooplaServiceImpl().storeDecisionTemplate(newDecisionTemplate);
    } catch (Exception e) {
        log.log(Level.WARNING, e.getLocalizedMessage(), e);
        resp.sendError(500);
        return;
    }

    log.info("returning to referer " + req.getHeader("referer"));
    resp.sendRedirect(
            req.getHeader("referer") != null && !"".equals(req.getHeader("referer")) ? req.getHeader("referer")
                    : "localhost:8088");
}

From source file:br.edu.ifpb.sislivros.model.ProcessadorFotos.java

public boolean salvarImagem(String path, FileItemStream item, String nameToSave) {
    try {//from   w w  w.j ava  2  s  .com
        File f = new File(path);
        //            File f = new File(path+File.separator+folder);            
        //            File parent = new File(f.getParent());
        //            
        //            if(!parent.exists())
        //                parent.mkdir();
        if (!f.exists()) {
            f.mkdir();
        }

        File savedFile = new File(f.getAbsoluteFile() + File.separator + nameToSave);
        FileOutputStream fos = new FileOutputStream(savedFile);

        InputStream is = item.openStream();

        int x = 0;
        byte[] b = new byte[1024];
        while ((x = is.read(b)) != -1) {
            fos.write(b, 0, x);
        }
        fos.flush();
        fos.close();

        return true;

    } catch (Exception ex) {
    }
    return false;
}

From source file:com.example.getstarted.util.CloudStorageHelper.java

/**
 * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
 * environment variable, appending a timestamp to end of the uploaded filename.
 *//*from  w  w  w. ja va 2  s  .c o m*/
public String uploadFile(FileItemStream fileStream, final String bucketName)
        throws IOException, ServletException {
    checkFileExtension(fileStream.getName());

    DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
    DateTime dt = DateTime.now(DateTimeZone.UTC);
    String dtString = dt.toString(dtf);
    final String fileName = fileStream.getName() + dtString;

    // the inputstream is closed by default, so we don't need to close it here
    BlobInfo blobInfo = storage.create(BlobInfo.newBuilder(bucketName, fileName)
            // Modify access list to allow all users with link to read file
            .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))).build(),
            fileStream.openStream());
    logger.log(Level.INFO, "Uploaded file {0} as {1}", new Object[] { fileStream.getName(), fileName });
    // return the public download link
    return blobInfo.getMediaLink();
}

From source file:com.northernwall.hadrian.handler.ImageHandler.java

private void updateImage(Request request, String serviceId) throws IOException, FileUploadException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        logger.warn("Trying to upload image for {} but content is not multipart", serviceId);
        return;//  w  w w .  jav  a2s.co  m
    }
    logger.info("Trying to upload image for {}", serviceId);
    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        if (!item.isFormField()) {
            String name = item.getName();
            name = name.replace(' ', '-').replace('&', '-').replace('<', '-').replace('>', '-')
                    .replace('/', '-').replace('\\', '-').replace('&', '-').replace('@', '-').replace('?', '-')
                    .replace('^', '-').replace('#', '-').replace('%', '-').replace('=', '-').replace('$', '-')
                    .replace('{', '-').replace('}', '-').replace('[', '-').replace(']', '-').replace('|', '-')
                    .replace(';', '-').replace(':', '-').replace('~', '-').replace('`', '-');
            dataAccess.uploadImage(serviceId, name, item.getContentType(), item.openStream());
        }
    }
}

From source file:com.google.livingstories.servlet.DataImportServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    startTime = System.currentTimeMillis();

    message = "";

    if (req.getContentType().contains("multipart/form-data")) {
        try {//w  w w  .  j a va  2 s . c  om
            ServletFileUpload upload = new ServletFileUpload();
            JSONObject data = null;
            boolean override = false;
            FileItemIterator iter = upload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (item.getFieldName().equals("override")) {
                    override = true;
                } else if (item.getFieldName().equals("data")) {
                    data = new JSONObject(Streams.asString(item.openStream()));
                }
            }
            checkRunState(override);
            inputData = data;
            setUp();
        } catch (FileUploadException ex) {
            throw new RuntimeException(ex);
        } catch (JSONException ex) {
            throw new RuntimeException(ex);
        }
    }

    try {
        process();
    } catch (Exception ex) {
        Writer result = new StringWriter();
        PrintWriter printWriter = new PrintWriter(result);
        ex.printStackTrace(printWriter);
        message = result.toString();
        runState = RunState.ERROR;
    } finally {
        if (runState != RunState.RUNNING) {
            tearDown();
        }
        Caches.clearAll();
    }

    resp.setContentType("text/html");
    resp.getWriter().append(message + "<br>" + runState.name());
}

From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java

/**
 * Creates a new request wrapper to handle multi-part data using methods
 * adapted from Jason Pell's multipart classes (see class description).
 * //  w  w w  .  ja  v a 2 s  .c  om
 * @param saveDir
 *            the directory to save off the file
 * @param servletRequest
 *            the request containing the multipart
 * @throws java.io.IOException
 *             is thrown if encoding fails.
 * @throws
 */
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {

    Integer delay = 3;
    UploadListener listener = null;
    DiskFileItemFactory fac = null;

    // Parse the request
    try {
        if (maxSize >= 0L && servletRequest.getContentLength() > maxSize) {
            servletRequest.setAttribute("error", "size");
            FileItemIterator it = new ServletFileUpload(fac).getItemIterator(servletRequest);
            // handle with each file:
            while (it.hasNext()) {
                FileItemStream item = it.next();
                if (item.isFormField()) {
                    List<String> values;
                    if (params.get(item.getFieldName()) != null) {
                        values = params.get(item.getFieldName());
                    } else {
                        values = new ArrayList<String>();
                    }
                    InputStream stream = item.openStream();
                    values.add(Streams.asString(stream));
                    params.put(item.getFieldName(), values);
                }
            }
            return;
        } else {
            listener = new UploadListener(servletRequest, delay);
            fac = new MonitoredDiskFileItemFactory(listener);
        }

        // Make sure that the data is written to file
        fac.setSizeThreshold(0);
        if (saveDir != null) {
            fac.setRepository(new File(saveDir));
        }
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        List items = upload.parseRequest(createRequestContext(servletRequest));

        for (Object item1 : items) {
            FileItem item = (FileItem) item1;
            if (log.isDebugEnabled())
                log.debug("Found item " + item.getFieldName());
            if (item.isFormField()) {
                log.debug("Item is a normal form field");
                List<String> values;
                if (params.get(item.getFieldName()) != null) {
                    values = params.get(item.getFieldName());
                } else {
                    values = new ArrayList<String>();
                }
                String charset = servletRequest.getCharacterEncoding();
                if (charset != null) {
                    values.add(item.getString(charset));
                } else {
                    values.add(item.getString());
                }
                params.put(item.getFieldName(), values);
            } else {
                log.debug("Item is a file upload");

                // Skip file uploads that don't have a file name - meaning
                // that no file was selected.
                if (item.getName() == null || item.getName().trim().length() < 1) {
                    log.debug("No file has been uploaded for the field: " + item.getFieldName());
                    continue;
                }

                String targetFileName = item.getName();

                if (!targetFileName.contains(":"))
                    item.write(new File(targetDirectory + targetFileName));

                //?Action
                List<FileItem> values;
                if (files.get(item.getFieldName()) != null) {
                    values = files.get(item.getFieldName());
                } else {
                    values = new ArrayList<FileItem>();
                }

                values.add(item);
                files.put(item.getFieldName(), values);
            }
        }
    } catch (Exception e) {
        log.error(e);
        errors.add(e.getMessage());
    }
}

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

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    Map<String, String> params = new HashMap<String, String>();
    boolean isConnexion = false;
    boolean isPassword = false;

    try {//from ww  w.  j a  v a2 s  . c om
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase("connexion")) {
                    isConnexion = true;
                }
                if (item.getFieldName().equalsIgnoreCase("password")) {
                    isPassword = true;
                }
                params.put(item.getFieldName(), Streams.asString(item.openStream(), "UTF-8"));
            }
        }
    } catch (FileUploadException e) {
        log.error(e);
    }

    if (isConnexion) {
        // user try to connect with an FMG account
        boolean isConnected = true;
        isConnected = connectFmgUser(p_request, p_response, params);
        if (isConnected) {
            String continueUrl = params.get("continue");
            if (continueUrl == null) {
                // by default, my games is the default url
                continueUrl = "/gamelist.jsp";
            }
            p_response.sendRedirect(continueUrl);
        }
        return;
    } else if (isPassword) {
        // user ask for his password to be send on his email
        String msg = "";
        FmgDataStore ds = new FmgDataStore(false);
        Query<EbAccount> query = ds.query(EbAccount.class).filter("m_email", params.get("email"));
        QueryResultIterator<EbAccount> it = query.iterator();
        if (!it.hasNext()) {
            msg = "l'adresse mail " + params.get("email") + " n'a pas t trouv";
        } else {
            EbAccount account = it.next();
            if (account.getLastPasswordAsk() != null && account.getLastPasswordAsk()
                    .getTime() > System.currentTimeMillis() - (1000 * 60 * 60 * 24)) {
                msg = "une seule demande par jour";
            } else if (account.getAuthProvider() != AuthProvider.Fmg) {
                msg = "ce compte FMG est associ a un compte google";
            } else {
                // all is ok, send a mail
                new FmgMessage("askPassword").sendEMail(account);

                msg = "un email a t envoy  " + account.getEmail();
                account.setLastPasswordAsk(new Date());
                ds.put(account);
            }
        }
        ds.close();

        p_response.sendRedirect("/password.jsp?msg=" + msg);
        return;
    } else {
        // update or create new account
        String msg = checkParams(params);
        if (msg != null) {
            p_response.sendRedirect("/account.jsp?msg=" + msg);
            return;
        }
        msg = saveAccount(p_request, p_response, params);
        if (msg != null) {
            p_response.sendRedirect("/account.jsp?msg=" + msg);
            return;
        } else {
            if (!Auth.isUserLogged(p_request, p_response)) {
                Auth.connectUser(p_request, params.get("login"));
            }
            if ("0".equalsIgnoreCase(params.get("accountid"))) {
                // return page new games
                p_response.sendRedirect("/gamelist.jsp?tab=0");
            } else {
                // stay editing profile
                p_response.sendRedirect("/profile.jsp?id=" + params.get("accountid"));
            }
            return;
        }
    }

}

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

public void uploadFolder(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    try {//from  ww  w  . j  a v  a2s . c  om
        ServletFileUpload upload = new ServletFileUpload();
        upload.setHeaderEncoding("UTF-8");
        FileItemIterator iterator = upload.getItemIterator(request);
        WPBFile ownerFile = null;
        Map<String, WPBFile> subfolderFiles = new HashMap<String, WPBFile>();

        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")) {

                String fullName = item.getName();
                String directoryPath = getDirectoryFromLongName(fullName);
                String fileName = getFileNameFromLongName(fullName);

                Map<String, WPBFile> tempSubFolders = checkAndCreateSubDirectory(directoryPath, ownerFile);
                subfolderFiles.putAll(tempSubFolders);

                // delete the existing file
                WPBFile existingFile = getFileFromDirectory(subfolderFiles.get(directoryPath), fileName);
                if (existingFile != null) {
                    deleteFile(existingFile, 0);
                }

                // create the file
                WPBFile file = new WPBFile();
                file.setExternalKey(adminStorage.getUniqueId());
                file.setFileName(fileName);
                file.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
                file.setDirectoryFlag(0);

                addFileToDirectory(subfolderFiles.get(directoryPath), file, item.openStream());

            }
        }

        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.webpagebytes.cms.controllers.FileController.java

public void upload(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    try {/*from  w  ww .j  a v  a  2  s.  c  o  m*/
        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:ai.ilikeplaces.servlets.ServletFileUploads.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request__//from   w w w  .  j  ava  2 s .co m
 * @param response__
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
protected void processRequest(final HttpServletRequest request__, final HttpServletResponse response__)
        throws ServletException, IOException {
    response__.setContentType("text/html;charset=UTF-8");
    Loggers.DEBUG.debug(logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0020"),
            request__.getLocale());
    PrintWriter out = response__.getWriter();

    final ResourceBundle gUI = PropertyResourceBundle.getBundle("ai.ilikeplaces.rbs.GUI");

    try {
        fileUpload: {
            if (!isFileUploadPermitted()) {
                errorTemporarilyDisabled(out);
                break fileUpload;
            }
            processSignOn: {
                final HttpSession session = request__.getSession(false);

                if (session == null) {
                    errorNoLogin(out);
                    break fileUpload;
                } else if (session.getAttribute(ServletLogin.HumanUser) == null) {
                    errorNoLogin(out);
                    break processSignOn;
                }

                processRequestType: {
                    @SuppressWarnings("unchecked")
                    final HumanUserLocal sBLoggedOnUserLocal = ((SessionBoundBadRefWrapper<HumanUserLocal>) session
                            .getAttribute(ServletLogin.HumanUser)).getBoundInstance();
                    try {
                        /*Check that we have a file upload request*/
                        final boolean isMultipart = ServletFileUpload.isMultipartContent(request__);
                        if (!isMultipart) {
                            LoggerFactory.getLogger(ServletFileUploads.class.getName()).error(
                                    logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0001"));
                            errorNonMultipart(out);

                            break processRequestType;
                        }

                        processRequest: {

                            // Create a new file upload handler
                            final ServletFileUpload upload = new ServletFileUpload();
                            // Parse the request
                            FileItemIterator iter = upload.getItemIterator(request__);
                            boolean persisted = false;

                            loop: {
                                Long locationId = null;
                                String photoDescription = null;
                                String photoName = null;
                                Boolean isPublic = null;
                                Boolean isPrivate = null;
                                boolean fileSaved = false;

                                while (iter.hasNext()) {
                                    FileItemStream item = iter.next();
                                    String name = item.getFieldName();
                                    String absoluteFileSystemFileName = FilePath;

                                    InputStream stream = item.openStream();
                                    @_fix(issue = "Handle no extension files")
                                    String usersFileName = null;
                                    String randomFileName = null;

                                    if (item.isFormField()) {
                                        final String value = Streams.asString(stream);
                                        Loggers.DEBUG.debug(
                                                logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0002"),
                                                name);
                                        Loggers.DEBUG.debug(
                                                logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0003"),
                                                value);
                                        if (name.equals("locationId")) {
                                            locationId = Long.parseLong(value);
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0004")));
                                        }

                                        if (name.equals("photoDescription")) {
                                            photoDescription = value;
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0005")));
                                        }

                                        if (name.equals("photoName")) {
                                            photoName = value;
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0006")));
                                        }

                                        if (name.equals("isPublic")) {
                                            if (!(value.equals("true") || value.equals("false"))) {
                                                throw new IllegalArgumentException(logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0007")
                                                        + value);
                                            }

                                            isPublic = Boolean.valueOf(value);
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0008")));

                                        }
                                        if (name.equals("isPrivate")) {
                                            if (!(value.equals("true") || value.equals("false"))) {
                                                throw new IllegalArgumentException(logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0007")
                                                        + value);
                                            }

                                            isPrivate = Boolean.valueOf(value);
                                            Loggers.DEBUG.debug("HELLO, I PROPERLY RECEIVED photoName.");

                                        }

                                    }
                                    if ((!item.isFormField())) {
                                        Loggers.DEBUG.debug((logMsgs.getString(
                                                "ai.ilikeplaces.servlets.ServletFileUploads.0009") + name));
                                        Loggers.DEBUG.debug((logMsgs
                                                .getString("ai.ilikeplaces.servlets.ServletFileUploads.0010")
                                                + item.getName()));
                                        // Process the input stream
                                        if (!(item.getName().lastIndexOf(".") > 0)) {
                                            errorFileType(out, item.getName());
                                            break processRequest;
                                        }

                                        usersFileName = (item.getName().indexOf("\\") <= 1 ? item.getName()
                                                : item.getName()
                                                        .substring(item.getName().lastIndexOf("\\") + 1));

                                        final String userUploadedFileName = item.getName();

                                        String fileExtension = "error";

                                        if (userUploadedFileName.toLowerCase().endsWith(".jpg")) {
                                            fileExtension = ".jpg";
                                        } else if (userUploadedFileName.toLowerCase().endsWith(".jpeg")) {
                                            fileExtension = ".jpeg";
                                        } else if (userUploadedFileName.toLowerCase().endsWith(".png")) {
                                            fileExtension = ".png";
                                        } else {
                                            errorFileType(out, gUI.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0019"));
                                            break processRequest;
                                        }

                                        randomFileName = getRandomFileName(locationId);

                                        randomFileName += fileExtension;

                                        final File uploadedFile = new File(
                                                absoluteFileSystemFileName += randomFileName);
                                        final FileOutputStream fos = new FileOutputStream(uploadedFile);
                                        while (true) {
                                            final int dataByte = stream.read();
                                            if (dataByte != -1) {
                                                fos.write(dataByte);
                                            } else {
                                                break;
                                            }

                                        }
                                        fos.close();
                                        stream.close();
                                        fileSaved = true;
                                    }

                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0011")
                                                    + locationId);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0012")
                                                    + fileSaved);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0013")
                                                    + photoDescription);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0014")
                                                    + photoName);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0015")
                                                    + isPublic);

                                    if (fileSaved && (photoDescription != null)) {
                                        persistData: {
                                            handlePublicPrivateness: {
                                                if ((isPublic != null) && isPublic && (locationId != null)) {
                                                    Return<PublicPhoto> r = DB
                                                            .getHumanCRUDPublicPhotoLocal(true)
                                                            .cPublicPhoto(sBLoggedOnUserLocal.getHumanUserId(),
                                                                    locationId, absoluteFileSystemFileName,
                                                                    photoName, photoDescription,
                                                                    new String(CDN + randomFileName), 4);
                                                    if (r.returnStatus() == 0) {
                                                        successFileName(out, usersFileName, logMsgs.getString(
                                                                "ai.ilikeplaces.servlets.ServletFileUploads.0016"));
                                                    } else {
                                                        errorBusy(out);
                                                    }

                                                } else if ((isPrivate != null) && isPrivate) {
                                                    Return<PrivatePhoto> r = DB
                                                            .getHumanCRUDPrivatePhotoLocal(true)
                                                            .cPrivatePhoto(sBLoggedOnUserLocal.getHumanUserId(),
                                                                    absoluteFileSystemFileName, photoName,
                                                                    photoDescription,
                                                                    new String(CDN + randomFileName));
                                                    if (r.returnStatus() == 0) {
                                                        successFileName(out, usersFileName, "private");
                                                    } else {
                                                        errorBusy(out);
                                                    }
                                                } else {
                                                    throw UNSUPPORTED_OPERATION_EXCEPTION;
                                                }
                                            }
                                        }
                                        /*We got what we need from the loop. Lets break it*/

                                        break loop;
                                    }

                                }

                            }
                            if (!persisted) {
                                errorMissingParameters(out);
                                break processRequest;
                            }

                        }

                    } catch (FileUploadException ex) {
                        Loggers.EXCEPTION.error(null, ex);
                        errorBusy(out);
                    }
                }

            }

        }
    } catch (final Throwable t_) {
        Loggers.EXCEPTION.error("SORRY! I ENCOUNTERED AN EXCEPTION DURING THE FILE UPLOAD", t_);
    }

}