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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

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

public void upload(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    try {/*from  w w  w  .ja  v  a 2s  .  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:com.liferay.faces.bridge.context.map.internal.MultiPartFormDataProcessorImpl.java

@Override
public Map<String, List<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig,
        FacesRequestParameterMap facesRequestParameterMap) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;

    PortletSession portletSession = clientDataRequest.getPortletSession();

    String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig);

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

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

    File uploadedFilesPath = new File(uploadedFilesDir, sessionId);

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

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

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

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

    // Determine the max file upload size threshold (in bytes).
    long uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getLongValue(portletConfig);

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

    // FACES-271: Include name+value pairs found in the ActionRequest.
    Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();

    for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {

        String parameterName = mapEntry.getKey();
        String[] parameterValues = mapEntry.getValue();

        if (parameterValues.length > 0) {

            for (String parameterValue : parameterValues) {
                facesRequestParameterMap.addValue(parameterName, parameterValue);
            }
        }
    }

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

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

        if (clientDataRequest instanceof ResourceRequest) {
            ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
        } else {
            ActionRequest actionRequest = (ActionRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
        }

        if (fileItemIterator != null) {

            int totalFiles = 0;
            String namespace = facesRequestParameterMap.getNamespace();

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

                try {
                    totalFiles++;

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

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

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

                    String fileName = null;

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

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

                    // If the current field is a simple form-field, then save the form field value in the map.
                    if (diskFileItem.isFormField()) {
                        String characterEncoding = clientDataRequest.getCharacterEncoding();
                        String requestParameterValue = null;

                        if (characterEncoding == null) {
                            requestParameterValue = diskFileItem.getString();
                        } else {
                            requestParameterValue = diskFileItem.getString(characterEncoding);
                        }

                        facesRequestParameterMap.addValue(fieldName, requestParameterValue);
                    } else {

                        File tempFile = diskFileItem.getStoreLocation();

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

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

                            String copiedFileName = stripIllegalCharacters(fileName);

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

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

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

                                if (headerNameItr != null) {

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

                                        if (headerValuesItr != null) {

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

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

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

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

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

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

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

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

    return uploadedFileMap;
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void createFile(HttpServletRequest req, HttpServletResponse resp, Document buildDoc)
        throws IndelibleWebAccessException, IOException, ServletException, FileUploadException {
    boolean completedOK = false;

    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(req);
    if (iter.hasNext()) {
        FileItemStream item = iter.next();
        String fieldName = item.getFieldName();
        FilePath dirPath = null;/*from  ww  w. ja v a2  s .com*/
        if (fieldName.equals("upfile")) {
            try {
                connection.startTransaction();
                String path = req.getPathInfo();
                String fileName = item.getName();
                if (fileName.indexOf('/') >= 0)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
                dirPath = FilePath.getFilePath(path);
                FilePath reqPath = dirPath.getChild(fileName);
                if (reqPath == null || reqPath.getNumComponents() < 2)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);

                // Should be an absolute path
                reqPath = reqPath.removeLeadingComponent();
                String fsIDStr = reqPath.getComponent(0);
                IndelibleFSVolumeIF volume = getVolume(fsIDStr);
                if (volume == null)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kVolumeNotFoundError,
                            null);
                FilePath createPath = reqPath.removeLeadingComponent();
                FilePath parentPath = createPath.getParent();
                FilePath childPath = createPath.getPathRelativeTo(parentPath);
                if (childPath.getNumComponents() != 1)
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
                IndelibleFileNodeIF parentNode = volume.getObjectByPath(parentPath.makeAbsolute());
                if (!parentNode.isDirectory())
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null);
                IndelibleDirectoryNodeIF parentDirectory = (IndelibleDirectoryNodeIF) parentNode;
                IndelibleFileNodeIF childNode = null;
                childNode = parentDirectory.getChildNode(childPath.getName());
                if (childNode == null) {
                    try {
                        CreateFileInfo childInfo = parentDirectory.createChildFile(childPath.getName(), true);
                        childNode = childInfo.getCreatedNode();
                    } catch (FileExistsException e) {
                        // Probably someone else beat us to it...
                        childNode = parentDirectory.getChildNode(childPath.getName());
                    }
                } else {

                }
                if (childNode.isDirectory())
                    throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotFile, null);

                IndelibleFSForkIF dataFork = childNode.getFork("data", true);
                dataFork.truncate(0);
                InputStream readStream = item.openStream();
                byte[] writeBuffer = new byte[1024 * 1024];
                int readLength;
                long bytesCopied = 0;
                int bufOffset = 0;
                while ((readLength = readStream.read(writeBuffer, bufOffset,
                        writeBuffer.length - bufOffset)) > 0) {
                    if (bufOffset + readLength == writeBuffer.length) {
                        dataFork.appendDataDescriptor(
                                new CASIDMemoryDataDescriptor(writeBuffer, 0, writeBuffer.length));
                        bufOffset = 0;
                    } else
                        bufOffset += readLength;
                    bytesCopied += readLength;
                }
                if (bufOffset != 0) {
                    // Flush out the final stuff
                    dataFork.appendDataDescriptor(new CASIDMemoryDataDescriptor(writeBuffer, 0, bufOffset));
                }
                connection.commit();
                completedOK = true;
            } catch (PermissionDeniedException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e);
            } catch (IOException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
            } catch (ObjectNotFoundException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
            } catch (ForkNotFoundException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kForkNotFound, e);
            } finally {
                if (!completedOK)
                    try {
                        connection.rollback();
                    } catch (IOException e) {
                        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
                    }
            }
            listPath(dirPath, buildDoc);
            return;
        }
    }
    throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
}

From source file:com.artgameweekend.projects.art.web.TagUploadServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {/*from ww w  .  j a v  a  2  s .  com*/

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(500000);
        res.setContentType(Constants.CONTENT_TYPE_TEXT);
        PrintWriter out = res.getWriter();
        byte[] image = null;

        Tag tag = new Tag();
        TagImage tagImage = new TagImage();
        TagThumbnail tagThumbnail = new TagThumbnail();
        String contentType = null;
        boolean bLandscape = false;

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

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                    if (Constants.PARAMATER_NAME.equals(item.getFieldName())) {
                        tag.setName(IOUtils.toString(in));
                    }
                    if (Constants.PARAMATER_LAT.equals(item.getFieldName())) {
                        tag.setLat(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LON.equals(item.getFieldName())) {
                        tag.setLon(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LANDSCAPE.equals(item.getFieldName())) {
                        bLandscape = IOUtils.toString(in).equals("on");
                    }
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    contentType = item.getContentType();

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

                    try {
                        image = IOUtils.toByteArray(in);
                    } finally {
                        IOUtils.closeQuietly(in);
                    }

                }
            }
        } catch (SizeLimitExceededException e) {
            out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                    + e.getActualSize() + ")");
        }

        contentType = (contentType != null) ? contentType : "image/jpeg";

        if (bLandscape) {
            image = rotate(image);
        }
        tagImage.setImage(image);
        tagImage.setContentType(contentType);
        tagThumbnail.setImage(createThumbnail(image));
        tagThumbnail.setContentType(contentType);

        TagImageDAO daoImage = new TagImageDAO();
        daoImage.create(tagImage);

        TagThumbnailDAO daoThumbnail = new TagThumbnailDAO();
        daoThumbnail.create(tagThumbnail);

        TagDAO dao = new TagDAO();
        tag.setKeyImage(tagImage.getKey());
        tag.setKeyThumbnail(tagThumbnail.getKey());
        tag.setDate(new Date().getTime());
        dao.create(tag);

    } catch (Exception ex) {

        throw new ServletException(ex);
    }
}

From source file:com.glaf.core.web.servlet.FileUploadServlet.java

public void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=UTF-8");
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    if (loginContext == null) {
        return;//w  w  w.  ja  v a  2 s. co m
    }
    String serviceKey = request.getParameter("serviceKey");
    String type = request.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap:" + paramMap);
    String rootDir = SystemProperties.getConfigRootPath();

    InputStream inputStream = null;
    try {
        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold ???? 8M
        diskFactory.setSizeThreshold(8 * FileUtils.MB_SIZE);
        // repository 
        diskFactory.setRepository(new File(rootDir + "/temp"));
        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
        if (maxUploadSize == 0) {
            maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB
        }
        maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;
        logger.debug("maxUploadSize:" + maxUploadSize);

        upload.setHeaderEncoding("UTF-8");
        upload.setSizeMax(maxUploadSize);
        upload.setFileSizeMax(maxUploadSize);
        String uploadDir = Constants.UPLOAD_PATH;

        if (ServletFileUpload.isMultipartContent(request)) {
            logger.debug("#################start upload process#########################");
            FileItemIterator iter = upload.getItemIterator(request);
            PrintWriter out = response.getWriter();
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    // ????
                    String autoCreatedDateDirByParttern = "yyyy/MM/dd";
                    String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(),
                            autoCreatedDateDirByParttern);

                    File savePath = new File(rootDir + uploadDir + autoCreatedDateDir);
                    if (!savePath.exists()) {
                        savePath.mkdirs();
                    }

                    String fileId = UUID32.getUUID();
                    String fileName = savePath + "/" + fileId;

                    BlobItem dataFile = new BlobItemEntity();
                    dataFile.setLastModified(System.currentTimeMillis());
                    dataFile.setCreateBy(loginContext.getActorId());
                    dataFile.setFileId(fileId);
                    dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId);
                    dataFile.setFilename(item.getName());
                    dataFile.setName(item.getName());
                    dataFile.setContentType(item.getContentType());
                    dataFile.setType(type);
                    dataFile.setStatus(0);
                    dataFile.setServiceKey(serviceKey);
                    getBlobService().insertBlob(dataFile);

                    inputStream = item.openStream();

                    FileUtils.save(fileName, inputStream);

                    logger.debug(fileName + " save ok.");

                    out.print(fileId);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.close(inputStream);
    }
}

From source file:n3phele.service.rest.impl.CommandResource.java

@Consumes(MediaType.MULTIPART_FORM_DATA)
@POST// w  w  w .  j a v a  2  s.c  o m
@Produces(MediaType.TEXT_PLAIN)
@Path("import")
@RolesAllowed("authenticated")
public Response importer(@Context HttpServletRequest request) {

    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                log.warning("Got a form field: " + item.getFieldName());
            } else {
                log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());
                //                  JAXBContext jc = JAXBContext.newInstance(CommandDefinitions.class);
                //                  Unmarshaller u = jc.createUnmarshaller();
                //                  CommandDefinitions a =   (CommandDefinitions) u.unmarshal(stream);
                JSONJAXBContext jc = new JSONJAXBContext(CommandDefinitions.class);
                JSONUnmarshaller u = jc.createJSONUnmarshaller();
                CommandDefinitions a = u.unmarshalFromJSON(stream, CommandDefinitions.class);
                StringBuilder response = new StringBuilder(
                        "Processing " + a.getCommand().size() + " commands\n");
                URI requestor = UserResource.toUser(securityContext).getUri();
                for (CommandDefinition cd : a.getCommand()) {
                    response.append(cd.getName());
                    response.append(".....");
                    Command existing = null;
                    try {
                        if (cd.getUri() != null && cd.getUri().toString().length() != 0) {
                            try {
                                existing = dao.command().get(cd.getUri());
                            } catch (NotFoundException e1) {
                                List<Command> others = null;
                                try {
                                    others = dao.command().getList(cd.getName());
                                    for (Command c : others) {
                                        if (c.getVersion().equals(cd.getVersion())
                                                || !requestor.equals(c.getOwner())) {
                                            existing = c;
                                        } else {
                                            if (c.isPreferred() && cd.isPreferred()) {
                                                c.setPreferred(false);
                                                dao.command().update(c);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    // not found
                                }
                            }
                        } else {
                            List<Command> others = null;
                            try {
                                others = dao.command().getList(cd.getName());
                                for (Command c : others) {
                                    if (c.getVersion().equals(cd.getVersion())
                                            || !requestor.equals(c.getOwner())) {
                                        existing = c;
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                // not found
                            }

                        }

                    } catch (NotFoundException e) {

                    }

                    if (existing == null) {
                        response.append(addCommand(cd));
                    } else {
                        // update or illegal operation
                        boolean isOwner = requestor.equals(existing.getOwner());
                        boolean mismatchedUri = (cd.getUri() != null && cd.getUri().toString().length() != 0)
                                && !cd.getUri().equals(existing.getUri());
                        log.info("requestor is " + requestor + " owner is " + existing.getOwner() + " isOwner "
                                + isOwner);
                        log.info("URI in definition is " + cd.getUri() + " existing is " + existing.getUri()
                                + " mismatchedUri " + mismatchedUri);

                        if (!isOwner || mismatchedUri) {
                            response.append("ignored: already exists");
                        } else {
                            response.append(updateCommand(cd, existing));
                            response.append("\nupdated uri " + existing.getUri());
                        }
                    }

                    response.append("\n");
                    //response.append("</li>");
                }
                //response.append("</ol>");
                return Response.ok(response.toString()).build();
            }
        }

    } catch (JAXBException e) {
        log.log(Level.WARNING, "JAXBException", e);

    } catch (FileUploadException e) {
        log.log(Level.WARNING, "FileUploadException", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "IOException", e);
    }
    return Response.notModified().build();
}

From source file:de.kp.ames.web.function.upload.UploadServiceImpl.java

public void doSetRequest(RequestContext ctx) {

    /*/* ww w .j a  va2  s.  c om*/
     * The result of the upload request, returned
     * to the requestor; note, that the result must
     * be a text response
     */
    boolean result = false;
    HttpServletRequest request = ctx.getRequest();

    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {

            /* 
             * Create new file upload handler
             */
            ServletFileUpload upload = new ServletFileUpload();

            /*
             * Parse the request
             */
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {

                FileItemStream fileItem = iter.next();
                if (fileItem.isFormField()) {
                    // not supported

                } else {

                    /* 
                     * Hook into the upload request to some virus scanning
                     * using the scanner factory of this application
                     */

                    byte[] bytes = FileUtil.getByteArrayFromInputStream(fileItem.openStream());
                    boolean checked = MalwareScanner.scanForViruses(bytes);

                    if (checked) {

                        String item = this.method.getAttribute(MethodConstants.ATTR_ITEM);
                        String type = this.method.getAttribute(MethodConstants.ATTR_TYPE);
                        if ((item == null) || (type == null)) {
                            this.sendNotImplemented(ctx);

                        } else {

                            String fileName = FilenameUtils.getName(fileItem.getName());
                            String mimeType = fileItem.getContentType();

                            try {
                                result = upload(item, type, fileName, mimeType, bytes);

                            } catch (Exception e) {
                                sendBadRequest(ctx, e);

                            }

                        }

                    }

                }

            }

        }

        /*
         * Send html response
         */
        if (result == true) {
            this.sendHTMLResponse(createHtmlSuccess(), ctx.getResponse());

        } else {
            this.sendHTMLResponse(createHtmlFailure(), ctx.getResponse());

        }

    } catch (Exception e) {
        this.sendBadRequest(ctx, e);

    } finally {
    }

}

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 {//ww w .j  a v  a  2 s .  co  m

        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:fi.helsinki.lib.simplerest.CommunitiesResource.java

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

        // 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:br.com.ifpb.bdnc.projeto.geo.servlets.CadastraImagem.java

private Image mountImage(HttpServletRequest request) {
    Image image = new Image();
    image.setCoord(new Coordenate());
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {//from   w ww . j av a 2 s  .  c o  m
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    InputStream in = item.openStream();
                    byte[] b = new byte[in.available()];
                    in.read(b);
                    if (item.getFieldName().equals("description")) {
                        image.setDescription(new String(b));
                    } else if (item.getFieldName().equals("authors")) {
                        image.setAuthors(new String(b));
                    } else if (item.getFieldName().equals("end")) {
                        image.setDate(
                                LocalDate.parse(new String(b), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    } else if (item.getFieldName().equals("latitude")) {
                        image.getCoord().setLat(new String(b));
                    } else if (item.getFieldName().equals("longitude")) {
                        image.getCoord().setLng(new String(b));
                    } else if (item.getFieldName().equals("heading")) {
                        image.getCoord().setHeading(new String(b));
                    } else if (item.getFieldName().equals("pitch")) {
                        image.getCoord().setPitch(new String(b));
                    } else if (item.getFieldName().equals("zoom")) {
                        image.getCoord().setZoom(new String(b));
                    }
                } else {
                    if (!item.getName().equals("")) {
                        MultipartData md = new MultipartData();
                        String folder = "historicImages";
                        md.setFolder(folder);
                        String path = request.getServletContext().getRealPath("/");
                        System.out.println(path);
                        String nameToSave = "pubImage" + Calendar.getInstance().getTimeInMillis()
                                + item.getName();
                        image.setImagePath(folder + "/" + nameToSave);
                        md.saveImage(path, item, nameToSave);
                        String imageMinPath = folder + "/" + "min" + nameToSave;
                        RedimencionadorImagem.resize(path, folder + "/" + nameToSave,
                                path + "/" + imageMinPath.toString(), IMAGE_MIN_WIDTH, IMAGE_MIM_HEIGHT);
                        image.setMinImagePath(imageMinPath);
                    }
                }
            }
        } catch (FileUploadException | IOException ex) {
            System.out.println("Erro ao manipular dados");
        }
    }
    return image;
}