Example usage for org.apache.commons.fileupload.util Streams asString

List of usage examples for org.apache.commons.fileupload.util Streams asString

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.util Streams asString.

Prototype

public static String asString(InputStream pStream) throws IOException 

Source Link

Document

This convenience method allows to read a org.apache.commons.fileupload.FileItemStream 's content into a string.

Usage

From source file:com.exilant.exility.core.HtmlRequestHandler.java

/**
 * //from  w  w  w .  jav  a  2  s . c o m
 * @param req
 * @param formIsSubmitted
 * @param hasSerializedDc
 * @param outData
 * @return service data that contains all input fields
 * @throws ExilityException
 */
public ServiceData createInDataForStream(HttpServletRequest req, boolean formIsSubmitted,
        boolean hasSerializedDc, ServiceData outData) throws ExilityException {
    ServiceData inData = new ServiceData();

    /**
     * this method is structured to handle simpler cases in the beginning if
     * form is not submitted, it has to be serialized data
     */
    if (formIsSubmitted == false) {
        this.extractSerializedData(req, hasSerializedDc, inData);
        return inData;
    }

    if (hasSerializedDc == false) {
        this.extractParametersAndFiles(req, inData);
        return inData;
    }

    // it is a form submit with serialized DC in it
    HttpSession session = req.getSession();
    try {
        if (ServletFileUpload.isMultipartContent(req) == false) {
            String txt = session.getAttribute("dc").toString();
            this.extractSerializedDc(txt, inData);

            this.extractFilesToDc(req, inData);
            return inData;
        }
        // complex case of file upload etc..
        ServletFileUpload fileUploader = new ServletFileUpload();
        fileUploader.setHeaderEncoding("UTF-8");
        FileItemIterator iterator = fileUploader.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream stream = iterator.next();
            InputStream inStream = null;
            try {
                inStream = stream.openStream();
                String fieldName = stream.getFieldName();
                if (stream.isFormField()) {
                    String fieldValue = Streams.asString(inStream);
                    if (fieldName.equals("dc")) {
                        this.extractSerializedDc(fieldValue, inData);
                    } else {
                        inData.addValue(fieldName, fieldValue);
                    }
                } else {
                    String fileContents = IOUtils.toString(inStream);
                    inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents);
                }
                inStream.close();
            } finally {
                IOUtils.closeQuietly(inStream);
            }

        }

        @SuppressWarnings("rawtypes")
        Enumeration e = req.getSession().getAttributeNames();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            if (name.equals("dc")) {
                this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData);
            }
            String value = req.getSession().getAttribute(name).toString();
            inData.addValue(name, value);
            System.out.println("name is: " + name + " value is: " + value);
        }
    } catch (Exception ioEx) {
        // nothing to do here
    }
    return inData;
}

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

public void uploadFolder(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    try {/* w ww . j  av a2s. co  m*/
        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.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp, OutputStream repoItemOutputStrem)
        throws IOException {

    log.info("Multipart detected");

    ServletFileUpload upload = new ServletFileUpload();

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

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            try (InputStream stream = item.openStream()) {
                if (item.isFormField()) {
                    // TODO What to do with this?
                    log.info("Form field {} with value {} detected.", name, Streams.asString(stream));
                } else {

                    // TODO Must we support multiple files uploading?
                    log.info("File field {} with file name detected.", name, item.getName());

                    log.info("Start to receive bytes (estimated bytes)",
                            Integer.toString(req.getContentLength()));
                    int bytes = IOUtils.copy(stream, repoItemOutputStrem);
                    resp.setStatus(SC_OK);
                    log.info("Bytes received: {}", Integer.toString(bytes));
                }
            }
        }

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

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

public void upload(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    try {// w w  w  . 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:ch.entwine.weblounge.contentrepository.impl.endpoint.FilesEndpoint.java

/**
 * Adds the resource content with language <code>language</code> to the
 * specified resource.//from   w w  w  .j a  v a2s.  c om
 * 
 * @param request
 *          the request
 * @param resourceId
 *          the resource identifier
 * @param languageId
 *          the language identifier
 * @param is
 *          the input stream
 * @return the resource
 */
@POST
@Path("/{resource}/content/{language}")
@Produces(MediaType.MEDIA_TYPE_WILDCARD)
public Response addFileContent(@Context HttpServletRequest request, @PathParam("resource") String resourceId,
        @PathParam("language") String languageId) {

    Site site = getSite(request);

    // Check the parameters
    if (resourceId == null)
        throw new WebApplicationException(Status.BAD_REQUEST);

    // Extract the language
    Language language = LanguageUtils.getLanguage(languageId);
    if (language == null) {
        throw new WebApplicationException(Status.NOT_FOUND);
    }

    // Get the resource
    Resource<?> resource = loadResource(request, resourceId, null);
    if (resource == null || resource.contents().isEmpty()) {
        throw new WebApplicationException(Status.NOT_FOUND);
    }

    String fileName = null;
    String mimeType = null;
    File uploadedFile = null;

    try {
        // Multipart form encoding?
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                ServletFileUpload payload = new ServletFileUpload();
                for (FileItemIterator iter = payload.getItemIterator(request); iter.hasNext();) {
                    FileItemStream item = iter.next();
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String fieldValue = Streams.asString(item.openStream());
                        if (StringUtils.isBlank(fieldValue))
                            continue;
                        if (OPT_MIMETYPE.equals(fieldName)) {
                            mimeType = fieldValue;
                        }
                    } else {
                        // once the body gets read iter.hasNext must not be invoked
                        // or the stream can not be read
                        fileName = StringUtils.trim(item.getName());
                        mimeType = StringUtils.trim(item.getContentType());
                        uploadedFile = File.createTempFile("upload-", null);
                        FileOutputStream fos = new FileOutputStream(uploadedFile);
                        try {
                            IOUtils.copy(item.openStream(), fos);
                        } catch (IOException e) {
                            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
                        } finally {
                            IOUtils.closeQuietly(fos);
                        }
                    }
                }
            } catch (FileUploadException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (IOException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            }
        }

        // Octet binary stream
        else {
            try {
                fileName = StringUtils.trimToNull(request.getHeader("X-File-Name"));
                mimeType = StringUtils.trimToNull(request.getParameter(OPT_MIMETYPE));
            } catch (UnknownLanguageException e) {
                throw new WebApplicationException(Status.BAD_REQUEST);
            }
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = request.getInputStream();
                if (is == null)
                    throw new WebApplicationException(Status.BAD_REQUEST);
                uploadedFile = File.createTempFile("upload-", null);
                fos = new FileOutputStream(uploadedFile);
                IOUtils.copy(is, fos);
            } catch (IOException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }

        }
        // Has there been a file in the request?
        if (uploadedFile == null)
            throw new WebApplicationException(Status.BAD_REQUEST);

        // A mime type would be nice as well
        if (StringUtils.isBlank(mimeType)) {
            mimeType = detectMimeTypeFromFile(fileName, uploadedFile);
            if (mimeType == null)
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }

        // Get the current user
        User user = securityService.getUser();
        if (user == null)
            throw new WebApplicationException(Status.UNAUTHORIZED);

        // Make sure the user has editing rights
        if (!SecurityUtils.userHasRole(user, SystemRole.EDITOR))
            throw new WebApplicationException(Status.UNAUTHORIZED);

        // Try to create the resource content
        InputStream is = null;
        ResourceContent content = null;
        ResourceContentReader<?> reader = null;
        ResourceSerializer<?, ?> serializer = serializerService
                .getSerializerByType(resource.getURI().getType());
        try {
            reader = serializer.getContentReader();
            is = new FileInputStream(uploadedFile);
            content = reader.createFromContent(is, user, language, uploadedFile.length(), fileName, mimeType);
        } catch (IOException e) {
            logger.warn("Error reading resource content {} from request", resource.getURI());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (ParserConfigurationException e) {
            logger.warn("Error configuring parser to read resource content {}: {}", resource.getURI(),
                    e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (SAXException e) {
            logger.warn("Error parsing udpated resource {}: {}", resource.getURI(), e.getMessage());
            throw new WebApplicationException(Status.BAD_REQUEST);
        } finally {
            IOUtils.closeQuietly(is);
        }

        URI uri = null;
        WritableContentRepository contentRepository = (WritableContentRepository) getContentRepository(site,
                true);
        try {
            is = new FileInputStream(uploadedFile);
            resource = contentRepository.putContent(resource.getURI(), content, is);
            uri = new URI(resource.getURI().getIdentifier());
        } catch (IOException e) {
            logger.warn("Error writing content to resource {}: {}", resource.getURI(), e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (IllegalStateException e) {
            logger.warn("Illegal state while adding content to resource {}: {}", resource.getURI(),
                    e.getMessage());
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
        } catch (ContentRepositoryException e) {
            logger.warn("Error adding content to resource {}: {}", resource.getURI(), e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (URISyntaxException e) {
            logger.warn("Error creating a uri for resource {}: {}", resource.getURI(), e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(is);
        }

        // Create the response
        ResponseBuilder response = Response.created(uri);
        response.type(MediaType.MEDIA_TYPE_WILDCARD);
        response.tag(ResourceUtils.getETagValue(resource));
        response.lastModified(ResourceUtils.getModificationDate(resource, language));
        return response.build();

    } finally {
        FileUtils.deleteQuietly(uploadedFile);
    }
}

From source file:ch.entwine.weblounge.contentrepository.impl.endpoint.FilesEndpoint.java

/**
 * Creates a file resource at the site's content repository by uploading
 * initial file content and returns the location to post updates to.
 * /*w  w  w. j a v a  2 s  .  c o  m*/
 * @param request
 *          the http request
 * @param resourceXml
 *          the new resource
 * @param path
 *          the path to store the resource at
 * @param mimeType
 *          the content mime type
 * @return response the resource location
 */
@POST
@Path("/uploads")
@Produces(MediaType.MEDIA_TYPE_WILDCARD)
public Response uploadFile(@Context HttpServletRequest request) {

    Site site = getSite(request);

    // Make sure the content repository is writable
    if (site.getContentRepository().isReadOnly()) {
        logger.warn("Attempt to write to read-only content repository {}", site);
        throw new WebApplicationException(Status.PRECONDITION_FAILED);
    }

    String fileName = null;
    Language language = null;
    String path = null;
    String mimeType = null;
    File uploadedFile = null;

    try {
        // Multipart form encoding?
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                ServletFileUpload payload = new ServletFileUpload();
                for (FileItemIterator iter = payload.getItemIterator(request); iter.hasNext();) {
                    FileItemStream item = iter.next();
                    String fieldName = item.getFieldName();
                    if (item.isFormField()) {
                        String fieldValue = Streams.asString(item.openStream());
                        if (StringUtils.isBlank(fieldValue))
                            continue;
                        if (OPT_PATH.equals(fieldName)) {
                            path = fieldValue;
                        } else if (OPT_LANGUAGE.equals(fieldName)) {
                            try {
                                language = LanguageUtils.getLanguage(fieldValue);
                            } catch (UnknownLanguageException e) {
                                throw new WebApplicationException(Status.BAD_REQUEST);
                            }
                        } else if (OPT_MIMETYPE.equals(fieldName)) {
                            mimeType = fieldValue;
                        }
                    } else {
                        // once the body gets read iter.hasNext must not be invoked
                        // or the stream can not be read
                        fileName = StringUtils.trim(item.getName());
                        mimeType = StringUtils.trim(item.getContentType());
                        uploadedFile = File.createTempFile("upload-", null);
                        FileOutputStream fos = new FileOutputStream(uploadedFile);
                        try {
                            IOUtils.copy(item.openStream(), fos);
                        } catch (IOException e) {
                            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
                        } finally {
                            IOUtils.closeQuietly(fos);
                        }
                    }
                }

            } catch (FileUploadException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (IOException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            }
        }

        // Octet binary stream
        else {
            try {
                fileName = StringUtils.trimToNull(request.getHeader("X-File-Name"));
                path = StringUtils.trimToNull(request.getParameter(OPT_PATH));
                mimeType = StringUtils.trimToNull(request.getParameter(OPT_MIMETYPE));
                language = LanguageUtils.getLanguage(request.getParameter(OPT_LANGUAGE));
            } catch (UnknownLanguageException e) {
                throw new WebApplicationException(Status.BAD_REQUEST);
            }

            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = request.getInputStream();
                if (is == null)
                    throw new WebApplicationException(Status.BAD_REQUEST);
                uploadedFile = File.createTempFile("upload-", null);
                fos = new FileOutputStream(uploadedFile);
                IOUtils.copy(is, fos);
            } catch (IOException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }

        }

        // Has there been a file in the request?
        if (uploadedFile == null)
            throw new WebApplicationException(Status.BAD_REQUEST);

        // Check the filename
        if (fileName == null) {
            logger.warn("No filename found for upload, request header 'X-File-Name' not specified");
            fileName = uploadedFile.getName();
        }

        // Make sure there is a language
        if (language == null) {
            language = LanguageUtils.getPreferredLanguage(request, site);
        }

        // A mime type would be nice as well
        if (StringUtils.isBlank(mimeType)) {
            mimeType = detectMimeTypeFromFile(fileName, uploadedFile);
            if (mimeType == null)
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }

        // Set owner and date created
        User user = securityService.getUser();
        if (user == null)
            throw new WebApplicationException(Status.UNAUTHORIZED);

        // Make sure the user has editing rights
        if (!SecurityUtils.userHasRole(user, SystemRole.EDITOR))
            throw new WebApplicationException(Status.UNAUTHORIZED);

        WritableContentRepository contentRepository = (WritableContentRepository) getContentRepository(site,
                true);

        // Create the resource uri
        URI uri = null;
        InputStream is = null;
        Resource<?> resource = null;
        ResourceURI resourceURI = null;
        logger.debug("Adding resource to {}", resourceURI);
        ResourceSerializer<?, ?> serializer = serializerService.getSerializerByMimeType(mimeType);
        if (serializer == null) {
            logger.debug("No specialized resource serializer found, using regular file serializer");
            serializer = serializerService.getSerializerByType(FileResource.TYPE);
        }

        // Create the resource
        try {
            is = new FileInputStream(uploadedFile);
            resource = serializer.newResource(site, is, user, language);
            resourceURI = resource.getURI();
        } catch (FileNotFoundException e) {
            logger.warn("Error creating resource at {} from image: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(is);
        }

        // If a path has been specified, set it
        if (path != null && StringUtils.isNotBlank(path)) {
            try {
                if (!path.startsWith("/"))
                    path = "/" + path;
                WebUrl url = new WebUrlImpl(site, path);
                resourceURI.setPath(url.getPath());

                // Make sure the resource doesn't exist
                if (contentRepository.exists(new GeneralResourceURIImpl(site, url.getPath()))) {
                    logger.warn("Tried to create already existing resource {} in site '{}'", resourceURI, site);
                    throw new WebApplicationException(Status.CONFLICT);
                }
            } catch (IllegalArgumentException e) {
                logger.warn("Tried to create a resource with an invalid path '{}': {}", path, e.getMessage());
                throw new WebApplicationException(Status.BAD_REQUEST);
            } catch (ContentRepositoryException e) {
                logger.warn("Resource lookup {} failed for site '{}'", resourceURI, site);
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            }
        }

        // Store the new resource
        try {
            uri = new URI(resourceURI.getIdentifier());
            contentRepository.put(resource, true);
        } catch (URISyntaxException e) {
            logger.warn("Error creating a uri for resource {}: {}", resourceURI, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (IOException e) {
            logger.warn("Error writing new resource {}: {}", resourceURI, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (IllegalStateException e) {
            logger.warn("Illegal state while adding new resource {}: {}", resourceURI, e.getMessage());
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
        } catch (ContentRepositoryException e) {
            logger.warn("Error adding new resource {}: {}", resourceURI, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }

        ResourceContent content = null;
        ResourceContentReader<?> reader = null;
        try {
            reader = serializer.getContentReader();
            is = new FileInputStream(uploadedFile);
            content = reader.createFromContent(is, user, language, uploadedFile.length(), fileName, mimeType);
        } catch (IOException e) {
            logger.warn("Error reading resource content {} from request", uri);
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (ParserConfigurationException e) {
            logger.warn("Error configuring parser to read resource content {}: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (SAXException e) {
            logger.warn("Error parsing udpated resource {}: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.BAD_REQUEST);
        } catch (Throwable t) {
            logger.warn("Unknown error while trying to read resource content {}: {}", uri, t.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(is);
            if (content == null) {
                try {
                    contentRepository.delete(resourceURI);
                } catch (Throwable t) {
                    logger.error("Error deleting orphan resource {}", resourceURI, t);
                }
            }
        }

        try {
            is = new FileInputStream(uploadedFile);
            resource = contentRepository.putContent(resource.getURI(), content, is);
        } catch (IOException e) {
            logger.warn("Error writing content to resource {}: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (IllegalStateException e) {
            logger.warn("Illegal state while adding content to resource {}: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
        } catch (ContentRepositoryException e) {
            logger.warn("Error adding content to resource {}: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(is);
        }

        // Create the response
        ResponseBuilder response = Response.created(uri);
        response.type(MediaType.MEDIA_TYPE_WILDCARD);
        response.tag(ResourceUtils.getETagValue(resource));
        response.lastModified(ResourceUtils.getModificationDate(resource));
        return response.build();

    } finally {
        FileUtils.deleteQuietly(uploadedFile);
    }
}

From source file:nu.kelvin.jfileshare.ajax.FileReceiverServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession();
    UserItem currentUser = (UserItem) session.getAttribute("user");
    if (currentUser != null && ServletFileUpload.isMultipartContent(req)) {
        Conf conf = (Conf) getServletContext().getAttribute("conf");
        // keep files of up to 10 MiB in memory 10485760
        FileItemFactory factory = new DiskFileItemFactory(10485760, new File(conf.getPathTemp()));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(conf.getFileSizeMax());

        // set file upload progress listener
        FileUploadListener listener = new FileUploadListener();
        session.setAttribute("uploadListener", listener);
        upload.setProgressListener(listener);

        File tempFile = File.createTempFile(String.format("%05d-", currentUser.getUid()), null,
                new File(conf.getPathTemp()));
        tempFile.deleteOnExit();/*from w  w w. j  av a 2  s  .c  om*/
        try {
            FileItem file = new FileItem();

            /* iterate over all uploaded items */
            FileItemIterator it = upload.getItemIterator(req);
            FileOutputStream filestream = null;

            while (it.hasNext()) {
                FileItemStream item = it.next();
                String name = item.getFieldName();
                InputStream instream = item.openStream();
                DigestOutputStream outstream = null;

                if (item.isFormField()) {
                    String value = Streams.asString(instream);
                    // logger.info(name + " : " + value);
                    /* not the file upload. Maybe the password field? */
                    if (name.equals("password") && !value.equals("")) {
                        logger.info("Uploaded file has password set");
                        file.setPwPlainText(value);
                    }
                    instream.close();
                } else {
                    // This is the file you're looking for
                    file.setName(item.getName());
                    file.setType(
                            item.getContentType() == null ? "application/octet-stream" : item.getContentType());
                    file.setUid(currentUser.getUid());

                    try {
                        filestream = new FileOutputStream(tempFile);
                        MessageDigest md = MessageDigest.getInstance("MD5");
                        outstream = new DigestOutputStream(filestream, md);
                        long filesize = IOUtils.copyLarge(instream, outstream);

                        if (filesize == 0) {
                            throw new Exception("File is empty.");
                        }
                        md = outstream.getMessageDigest();
                        file.setMd5sum(toHex(md.digest()));
                        file.setSize(filesize);

                    } finally {
                        if (outstream != null) {
                            try {
                                outstream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        if (filestream != null) {
                            try {
                                filestream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        if (instream != null) {
                            try {
                                instream.close();
                            } catch (IOException ignored) {
                            }
                        }
                    }
                }
            }
            /* All done. Save the new file */
            if (conf.getDaysFileExpiration() != 0) {
                file.setDaysToKeep(conf.getDaysFileExpiration());
            }
            if (file.create(ds, req.getRemoteAddr())) {
                File finalFile = new File(conf.getPathStore(), Integer.toString(file.getFid()));
                tempFile.renameTo(finalFile);
                logger.log(Level.INFO, "User {0} storing file \"{1}\" in the filestore",
                        new Object[] { currentUser.getUid(), file.getName() });
                req.setAttribute("msg",
                        "File <strong>\"" + Helpers.htmlSafe(file.getName())
                                + "\"</strong> uploaded successfully. <a href='" + req.getContextPath()
                                + "/file/edit/" + file.getFid() + "'>Click here to edit file</a>");
                req.setAttribute("javascript", "parent.uploadComplete('info');");
            } else {
                req.setAttribute("msg", "Unable to contact the database");
                req.setAttribute("javascript", "parent.uploadComplete('critical');");
            }
        } catch (SizeLimitExceededException e) {
            tempFile.delete();
            req.setAttribute("msg", "File is too large. The maximum size of file uploads is "
                    + FileItem.humanReadable(conf.getFileSizeMax()));
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } catch (FileUploadException e) {
            tempFile.delete();
            req.setAttribute("msg", "Unable to upload file");
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } catch (Exception e) {
            tempFile.delete();
            req.setAttribute("msg",
                    "Unable to upload file. ".concat(e.getMessage() == null ? "" : e.getMessage()));
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } finally {
            session.setAttribute("uploadListener", null);
        }
        ServletContext app = getServletContext();
        RequestDispatcher disp = app.getRequestDispatcher("/templates/AjaxDummy.jsp");
        disp.forward(req, resp);
    }
}

From source file:org.apache.jsp.fileUploader_jsp.java

public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;//from w  w w  .jav  a  2 s.  c  o m
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
        response.setContentType("text/html; charset=utf-8");
        pageContext = _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("<!--\n");
        out.write("Copyright 2012 The Infinit.e Open Source Project\n");
        out.write("\n");
        out.write("Licensed under the Apache License, Version 2.0 (the \"License\");\n");
        out.write("you may not use this file except in compliance with the License.\n");
        out.write("You may obtain a copy of the License at\n");
        out.write("\n");
        out.write("  http://www.apache.org/licenses/LICENSE-2.0\n");
        out.write("\n");
        out.write("Unless required by applicable law or agreed to in writing, software\n");
        out.write("distributed under the License is distributed on an \"AS IS\" BASIS,\n");
        out.write("WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n");
        out.write("See the License for the specific language governing permissions and\n");
        out.write("limitations under the License.\n");
        out.write("-->\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
        out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
        out.write("<head>\n");
        out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n");
        out.write("<title>Infinit.e File Upload Tool</title>\n");
        out.write("<style media=\"screen\" type=\"text/css\">\n");
        out.write("\n");
        out.write("body \n");
        out.write("{\n");
        out.write("\tfont: 14px Arial,sans-serif;\n");
        out.write("}\n");
        out.write("h2\n");
        out.write("{\n");
        out.write("\tfont-family: \"Times New Roman\";\n");
        out.write("\tfont-style: italic;\n");
        out.write("\tfont-variant: normal;\n");
        out.write("\tfont-weight: normal;\n");
        out.write("\tfont-size: 24px;\n");
        out.write("\tline-height: 29px;\n");
        out.write("\tfont-size-adjust: none;\n");
        out.write("\tfont-stretch: normal;\n");
        out.write("\t-x-system-font: none;\n");
        out.write("\tcolor: #d2331f;\n");
        out.write("\tmargin-bottom: 25px;\n");
        out.write("}\n");
        out.write(".show {\n");
        out.write("display: ;\n");
        out.write("visibility: visible;\n");
        out.write("}\n");
        out.write(".hide {\n");
        out.write("display: none;\n");
        out.write("visibility: hidden;\n");
        out.write("}\n");
        out.write("</style>\n");
        out.write("<script language=\"javascript\" src=\"AppConstants.js\"> </script>\n");
        out.write("</head>\n");
        out.write("\n");
        out.write("<body onload=\"populate()\">\n");

        if (API_ROOT == null) {
            ServletContext context = session.getServletContext();
            String realContextPath = context.getRealPath("/");
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("javascript");
            try { // EC2 Machines
                FileReader reader = new FileReader(realContextPath + "/AppConstants.js");
                engine.eval(reader);
                reader.close();
                engine.eval("output = getEndPointUrl();");
                API_ROOT = (String) engine.get("output");
                SHARE_ROOT = API_ROOT + "share/get/";
            } catch (Exception je) {
                try { ////////////Windows + Tomcat
                    FileReader reader = new FileReader(realContextPath + "\\..\\AppConstants.js");
                    engine.eval(reader);
                    reader.close();
                    engine.eval("output = getEndPointUrl();");
                    API_ROOT = (String) engine.get("output");
                    SHARE_ROOT = API_ROOT + "share/get/";
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
            if (null == API_ROOT) {
                // Default to localhost
                API_ROOT = "http://localhost:8080/api/";
                SHARE_ROOT = "$infinite/share/get/";
            }

            if (API_ROOT.contains("localhost"))
                localCookie = true;
            else
                localCookie = false;
        }
        Boolean isLoggedIn = isLoggedIn(request, response);
        if (isLoggedIn == null) {
            out.println("The Infinit.e API cannot be reached.");
            out.println(API_ROOT);
        }

        else if (isLoggedIn == true) {
            showAll = (request.getParameter("sudo") != null);
            DEBUG_MODE = (request.getParameter("debug") != null);
            communityList = generateCommunityList(request, response);

            if (request.getParameter("logout") != null) {
                logOut(request, response);
                out.println("<div style=\" text-align: center;\">");
                out.println("<meta http-equiv=\"refresh\" content=\"0\">");
                out.println("</div>");
            } else {

                out.println("<div style=\" text-align: center;\">");
                String contentType = request.getContentType();
                if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

                    //      Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                    //      Parse the request
                    FileItemIterator iter = upload.getItemIterator(request);
                    byte[] fileBytes = null;
                    String fileDS = null;
                    byte[] iconBytes = null;
                    String iconDS = null;
                    Set<String> communities = new HashSet<String>();
                    boolean isFileSet = false;
                    while (iter.hasNext()) {
                        FileItemStream item = iter.next();
                        String name = item.getFieldName();
                        InputStream stream = item.openStream();
                        if (item.isFormField()) {
                            if (name.equalsIgnoreCase("communities")) {
                                communities.add(Streams.asString(stream));
                            } else
                                request.setAttribute(name, Streams.asString(stream));

                            //out.println("<b>" + name + ":</b>" + request.getAttribute(name).toString()+"</br>");
                        } else {
                            if (name.equalsIgnoreCase("file")) {
                                if (!item.getName().equals(""))
                                    isFileSet = true;
                                fileDS = item.getContentType();
                                fileBytes = IOUtils.toByteArray(stream);

                                // Check if this should be a java-archive (rather than just an octet stream)
                                if (fileDS.equals("application/octet-stream")) {
                                    ZipInputStream zis = new ZipInputStream(
                                            new ByteArrayInputStream(fileBytes));
                                    ZipEntry entry;
                                    while ((entry = zis.getNextEntry()) != null) {
                                        if (entry.getName().endsWith(".class")) {
                                            fileDS = "application/java-archive";
                                            break;
                                        }
                                    }
                                }
                                // Reset stream, and read
                            }
                        }
                    }

                    ////////////////////////////////////Delete Share ////////////////////////////////
                    if (request.getAttribute("deleteId") != null) {
                        String fileId = request.getAttribute("deleteId").toString();
                        if (fileId != null && fileId != "")
                            removeFromShare(fileId, request, response).toString();

                    }
                    ////////////////////////////////////Update Community Info////////////////////////////////
                    else if (null == fileBytes) {
                        String shareId = request.getAttribute("DBId").toString();
                        if (shareId != null && shareId != "")
                            addRemoveCommunities(shareId, communities, request, response);
                    } else {
                        //////////////////////////////////////////////////////////////////////////////////

                        Boolean newUpload = (request.getAttribute("DBId").toString().length() == 0);

                        ///////////////////////////////// SWF Manip  /////////////////////////////////
                        String shareId = request.getAttribute("DBId").toString();
                        String fileUrl = "";
                        String fileId = "";
                        String bin = request.getAttribute("binary").toString();
                        if (request.getAttribute("title") != null && request.getAttribute("description") != null
                                && fileBytes != null) {
                            if (!isFileSet) //if not a binary file or file was not changed
                            {
                                fileId = shareId;
                                if (shareId != null && shareId != "")
                                    addRemoveCommunities(shareId, communities, request, response);
                                out.println("File was not set, just updated communities.");
                            } else if (bin.equals("null")) //is a json file, make sure its okay and upload it
                            {
                                fileId = UpdateToShare(fileBytes, fileDS,
                                        request.getAttribute("title").toString(),
                                        request.getAttribute("description").toString(), shareId, communities,
                                        true, request.getAttribute("type").toString(), newUpload, request,
                                        response);
                            } else //is a binary, do normal
                            {
                                fileId = UpdateToShare(fileBytes, fileDS,
                                        request.getAttribute("title").toString(),
                                        request.getAttribute("description").toString(), shareId, communities,
                                        false, request.getAttribute("type").toString(), newUpload, request,
                                        response);
                            }

                            if (fileId.contains("Failed")) {
                                out.println(fileId);
                            } else {
                                fileUrl = SHARE_ROOT + fileId;
                                if (newUpload)
                                    out.println(
                                            "You have successfully added a file to the share, its location is: "
                                                    + fileUrl);
                                else
                                    out.println(
                                            "You have successfully updated a file on the share, its location is: "
                                                    + fileUrl);
                            }
                        } else {
                            fileUrl = null;
                            out.println("Error: Not enough information provided for file Upload");
                        }

                        ///////////////////////////////// End File Manip  /////////////////////////////////

                        out.println("</div>");
                    }
                } else {
                }

                out.write("\n");
                out.write("\t\n");
                out.write("\t<script>\n");
                out.write("\tfunction clearCommList()\n");
                out.write("\t\t{\n");
                out.write("\t\t\tmult_comms = document.getElementById('communities');\n");
                out.write("\t\t\tfor ( var i = 0, l = mult_comms.options.length, o; i < l; i++ )\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t  o = mult_comms.options[i];\n");
                out.write("\t\t\t  o.selected = false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction highlightComms(commList)\n");
                out.write("\t\t{\n");
                out.write("\t\t\tmult_comms = document.getElementById('communities');\n");
                out.write("\t\t\tfor ( var i = 0, l = mult_comms.options.length, o; i < l; i++ )\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t  o = mult_comms.options[i];\n");
                out.write("\t\t\t  if(commList.indexOf(o.value) == -1)\n");
                out.write("\t\t\t\to.selected = false;\n");
                out.write("\t\t\t  else  \n");
                out.write("\t\t\t  \to.selected = true;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t}\n");
                out.write("\tfunction populate()\n");
                out.write("\t{\n");
                out.write("\t\tvar typerow = document.getElementById('typerow');\n");
                out.write("\t\tvar type = document.getElementById('type');\n");
                out.write("\t\tvar title = document.getElementById('title');\n");
                out.write("\t\tvar description = document.getElementById('description');\n");
                out.write("\t\tvar file = document.getElementById('file');\n");
                out.write("\t\tvar created = document.getElementById('created');\n");
                out.write("\t\tvar DBId = document.getElementById('DBId');\n");
                out.write("\t\tvar deleteId = document.getElementById('deleteId');\n");
                out.write("\t\tvar deleteButton = document.getElementById('deleteButton');\n");
                out.write("\t\tvar share_url = document.getElementById('share_url');\n");
                out.write("\t\tvar owner_text = document.getElementById('owner_text');\n");
                out.write("\t\tvar owner = document.getElementById('owner');\n");
                out.write("\t\tvar url_row = document.getElementById('url_row');\n");
                out.write("\t\tvar dropdown = document.getElementById(\"upload_info\");\n");
                out.write("\t\tvar list = dropdown.options[dropdown.selectedIndex].value;\n");
                out.write("\t\tvar binary = document.getElementById(\"binary\");\n");
                out.write("\t\t\n");
                out.write("\t\tif (list == \"new\")\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle.value = \"\";\n");
                out.write("\t\t\tdescription.value = \"\";\n");
                out.write("\t\t\ttype.value = \"binary\";\n");
                out.write("\t\t\tcreated.value = \"\";\n");
                out.write("\t\t\tDBId.value = \"\";\n");
                out.write("\t\t\tdeleteId.value = \"\";\n");
                out.write("\t\t\tshare_url.value = \"\";\n");
                out.write("\t\t\towner.value = \"\";\n");
                out.write("\t\t\ttyperow.className = \"hide\";\n");
                out.write("\t\t\turl_row.className = \"hide\";\n");
                out.write("\t\t\towner.className = \"hide\";\n");
                out.write("\t\t\towner_text.className = \"hide\";\n");
                out.write("\t\t\tdeleteButton.className = \"hide\";\n");
                out.write("\t\t\tclearCommList();\n");
                out.write("\t\t\tbinary.value = \"\";\n");
                out.write("\t\t\treturn;\n");
                out.write("\t\t}\n");
                out.write("\t\t\n");
                out.write("\t\tif ( list == \"newJSON\")\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle.value = \"\";\n");
                out.write("\t\t\tdescription.value = \"\";\n");
                out.write("\t\t\ttype.value = \"\";\n");
                out.write("\t\t\tcreated.value = \"\";\n");
                out.write("\t\t\tDBId.value = \"\";\n");
                out.write("\t\t\tdeleteId.value = \"\";\n");
                out.write("\t\t\tshare_url.value = \"\";\n");
                out.write("\t\t\towner.value = \"\";\n");
                out.write("\t\t\ttyperow.className = \"show\";\n");
                out.write("\t\t\turl_row.className = \"hide\";\n");
                out.write("\t\t\towner.className = \"hide\";\n");
                out.write("\t\t\towner_text.className = \"hide\";\n");
                out.write("\t\t\tdeleteButton.className = \"hide\";\n");
                out.write("\t\t\tclearCommList();\n");
                out.write("\t\t\tbinary.value = \"null\";\n");
                out.write("\t\t\treturn;\n");
                out.write("\t\t}\n");
                out.write("\t\t\n");
                out.write("\t\t//_id, created, title, description\n");
                out.write("\t\tsplit = list.split(\"$$$\");\n");
                out.write("\t\t\n");
                out.write("\t\tres_id = split[0];\n");
                out.write("\t\tres_created = split[1];\n");
                out.write("\t\tres_title = split[2];\n");
                out.write("\t\tres_description = split[3];\n");
                out.write("\t\tres_url = split[4];\n");
                out.write("\t\tcommunities = split[5];\n");
                out.write("\t\tres_owner = split[6];\n");
                out.write("\t\tres_binary = split[7];\t\t\n");
                out.write("\t\tres_type = split[8];\t\t\t\n");
                out.write("\t\t\n");
                out.write("\t\tif ( res_binary == \"null\" )\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttyperow.className = \"show\";\n");
                out.write("\t\t}\n");
                out.write("\t\telse\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttyperow.className = \"hide\";\n");
                out.write("\t\t}\n");
                out.write("\t\ttitle.value = res_title;\n");
                out.write("\t\tdescription.value = res_description;\n");
                out.write("\t\tcreated.value = res_created;\n");
                out.write("\t\tDBId.value = res_id;\n");
                out.write("\t\tdeleteId.value = res_id;\n");
                out.write("\t\tshare_url.value = res_url;\n");
                out.write("\t\towner.value = res_owner;\t\t\n");
                out.write("\t\tdeleteButton.className = \"show\";\n");
                out.write("\t\towner.className = \"show\";\n");
                out.write("\t\towner_text.className = \"show\";\n");
                out.write("\t\turl_row.className = \"show\";\n");
                out.write("\t\thighlightComms(communities);\t\t\n");
                out.write("\t\tbinary.value = res_binary;\n");
                out.write("\t\ttype.value = res_type;\n");
                out.write("\t}\n");
                out.write("\t\tfunction validate_fields()\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle = document.getElementById('title').value;\n");
                out.write("\t\t\tdescription = document.getElementById('description').value;\n");
                out.write("\t\t\tfile = document.getElementById('file').value;\n");
                out.write("\t\t\tbinary = document.getElementById(\"binary\").value;\n");
                out.write("\t\t\ttype = document.getElementById(\"type\").value;\n");
                out.write("\t\t\t//share_url = document.getElementById('share_url').value;\n");
                out.write("\t\t\t//file_url = document.getElementById('file_url').value;\n");
                out.write("\t\t\t//file_check = document.getElementById('file_check').checked;\n");
                out.write("\t\t\t\n");
                out.write("\t\t\tif (title == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a title.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\tif (description == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a description.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\tif ( binary == \"null\" && type == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a type.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\t\n");
                out.write("\t\t\t\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction confirmDelete()\n");
                out.write("\t\t{\n");
                out.write(
                        "\t\t\tvar agree=confirm(\"Are you sure you wish to Delete this file from the File Share?\");\n");
                out.write("\t\t\tif (agree)\n");
                out.write("\t\t\t\treturn true ;\n");
                out.write("\t\t\telse\n");
                out.write("\t\t\t\treturn false ;\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction showResults()\n");
                out.write("\t\t{\n");
                out.write("\t\t\tvar title = document.getElementById('DBId').value;\n");
                out.write("\t\t\tvar url = getEndPointUrl() + \"share/get/\" + title;\n");
                out.write("\t\t\twindow.open(url, '_blank');\n");
                out.write("\t\t\twindow.focus();\t\t\t\n");
                out.write("\t\t}\n");
                out.write("\t\t// -->\n");
                out.write("\t\t</script>\n");
                out.write("\t</script>\n");
                out.write(
                        "\t\t<div id=\"uploader_outter_div\" name=\"uploader_outter_div\" align=\"center\" style=\"width:100%\" >\n");
                out.write(
                        "\t    \t<div id=\"uploader_div\" name=\"uploader_div\" style=\"border-style:solid; border-color:#999999; border-radius: 10px; width:475px; margin:auto\">\n");
                out.write("\t        \t<h2>File Uploader</h2>\n");
                out.write("\t        \t<form id=\"search_form\" name=\"search_form\" method=\"get\">\n");
                out.write("\t        \t\t<div align=\"center\"\">\n");
                out.write("\t        \t\t<label for=\"ext\">Filter On</label>\n");
                out.write("\t\t\t\t\t  <select name=\"ext\" id=\"ext\" onchange=\"this.form.submit();\">\n");
                out.write("\t\t\t\t\t    ");

                out.print(populateMediaTypes(request, response));

                out.write("\n");
                out.write("\t\t\t\t\t  </select>\n");
                out.write("\t\t\t\t\t </div>\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t        \t</form>\n");
                out.write(
                        "\t        \t<form id=\"delete_form\" name=\"delete_form\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"javascript:return confirmDelete()\" >\n");
                out.write(
                        "\t        \t\t<select id=\"upload_info\" onchange=\"populate()\" name=\"upload_info\"><option value=\"new\">Upload New File</option><option value=\"newJSON\">Upload New JSON</option> ");

                out.print(populatePreviousUploads(request, response));

                out.write("</select>\n");
                out.write(
                        "\t        \t\t<input type=\"submit\" name=\"deleteButton\" id=\"deleteButton\" class=\"hidden\" value=\"Delete\" />\n");
                out.write("\t        \t\t<input type=\"hidden\" name=\"deleteId\" id=\"deleteId\" />\n");
                out.write("\t        \t\t<input type=\"hidden\" name=\"deleteFile\" id=\"deleteFile\" />\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t        \t</form>\n");
                out.write(
                        "\t            <form id=\"upload_form\" name=\"upload_form\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"javascript:return validate_fields();\" >\n");
                out.write(
                        "\t                <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"padding-left:10px; padding-right:10px\">\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td colspan=\"2\" align=\"center\"></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>Title:</td>\n");
                out.write(
                        "\t                    <td><input type=\"text\" name=\"title\" id=\"title\" size=\"39\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>Description:</td>\n");
                out.write(
                        "\t                    <td><textarea rows=\"4\" cols=\"30\" name=\"description\" id=\"description\" ></textarea></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr id=\"typerow\">\n");
                out.write("\t                    <td>Type:</td>\n");
                out.write(
                        "\t                    <td><input type=\"text\" name=\"type\" id=\"type\" size=\"39\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                  \t<td>Communities:</td>\n");
                out.write("\t                  \t<td>");

                out.print(communityList);

                out.write("</td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                  \t<td id=\"owner_text\">Owner:</td>\n");
                out.write("\t                  \t<td>\n");
                out.write(
                        "\t                    <input type=\"text\" name=\"owner\" id=\"owner\" readonly=\"readonly\" size=\"25\" />\n");
                out.write("\t                  \t</td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>File:</td>\n");
                out.write("\t                    <td><input type=\"file\" name=\"file\" id=\"file\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr id=\"url_row\" class=\"hide\">\n");
                out.write("\t                  \t<td>Share URL:</td>\n");
                out.write(
                        "\t                  \t<td><input type=\"text\" name=\"share_url\" id=\"share_url\" readonly=\"readonly\" size=\"38\"/>\n");
                out.write(
                        "\t                  \t<input type=\"button\" onclick=\"showResults()\" value=\"View\"/>\n");
                out.write("\t                  \t</td>\n");
                out.write("\t                \t<td></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write(
                        "\t                    <td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"Submit\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                </table>\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"created\" id=\"created\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"DBId\" id=\"DBId\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"fileUrl\" id=\"fileUrl\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"binary\" id=\"binary\" />\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t\t\t\t</form>\n");
                out.write("\t        </div>\n");
                out.write("\t        <form id=\"logout_form\" name=\"logout_form\" method=\"post\">\n");
                out.write(
                        "\t        \t<input type=\"submit\" name=\"logout\" id = \"logout\" value=\"Log Out\" />\n");
                out.write("\t        </form>\n");
                out.write("\t    </div>\n");
                out.write("\t    </p>\n");
                out.write("\t\n");

            }
        } else if (isLoggedIn == false) {
            //localCookie =(request.getParameter("local") != null);
            //System.out.println("LocalCookie = " + localCookie.toString());
            String errorMsg = "";
            if (request.getParameter("logintext") != null || request.getParameter("passwordtext") != null) {
                if (logMeIn(request.getParameter("logintext"), request.getParameter("passwordtext"), request,
                        response)) {
                    showAll = (request.getParameter("sudo") != null);
                    out.println("<meta http-equiv=\"refresh\" content=\"0\">");
                    out.println("Login Success");
                } else {
                    errorMsg = "Log in Failed, Please Try again";
                }

            }

            out.write("\n");
            out.write("\n");
            out.write("<script>\n");
            out.write("\tfunction validate_fields()\n");
            out.write("\t{\n");
            out.write("\t\tuname = document.getElementById('logintext').value;\n");
            out.write("\t\tpword = document.getElementById('passwordtext').value;\n");
            out.write("\t\t\n");
            out.write("\t\tif (uname == \"\")\n");
            out.write("\t\t{\n");
            out.write("\t\t\talert('Please provide your username.');\n");
            out.write("\t\t\treturn false;\n");
            out.write("\t\t}\n");
            out.write("\t\tif (pword == \"\")\n");
            out.write("\t\t{\n");
            out.write("\t\t\talert('Please provide your password.');\n");
            out.write("\t\t\treturn false;\n");
            out.write("\t\t}\n");
            out.write("\t}\n");
            out.write("\n");
            out.write("\n");
            out.write("</script>\n");
            out.write(
                    "\t<div id=\"login_outter_div\" name=\"login_outter_div\" align=\"center\" style=\"width:100%\" >\n");
            out.write(
                    "    \t<div id=\"login_div\" name=\"login_div\" style=\"border-style:solid; border-color:#999999; border-radius: 10px; width:450px; margin:auto\">\n");
            out.write("        \t<h2>Login</h2>\n");
            out.write(
                    "            <form id=\"login_form\" name=\"login_form\" method=\"post\" onsubmit=\"javascript:return validate_fields();\" >\n");
            out.write(
                    "                <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"padding-left:10px\">\n");
            out.write("                  <tr>\n");
            out.write("                    <td>User Name</td>\n");
            out.write("                    <td>&nbsp;</td>\n");
            out.write("                    <td>Password</td>\n");
            out.write("                  </tr>\n");
            out.write("                  <tr>\n");
            out.write(
                    "                    <td><input type=\"text\" name=\"logintext\" id=\"logintext\" width=\"190px\" /></td>\n");
            out.write("                    <td>&nbsp;</td>\n");
            out.write(
                    "                    <td><input type=\"password\" name=\"passwordtext\" id=\"passwordtext\" width=\"190px\" /></td>\n");
            out.write("                  </tr>\n");
            out.write("                  <tr>\n");
            out.write(
                    "                    <td colspan=\"3\" align=\"right\"><input name=\"Login\" type=\"submit\" value=\"Login\" /></td>\n");
            out.write("                  </tr>\n");
            out.write("                </table>\n");
            out.write("\t\t\t</form>\n");
            out.write("        </div>\n");
            out.write("    </div>\n");
            out.write("\t<div style=\"color: red; text-align: center;\"> ");
            out.print(errorMsg);
            out.write(" </div>\n");

        }

        out.write("\n");
        out.write("    \n");
        out.write("    \n");
        out.write("</body>\n");
        out.write("</html>");
    } catch (Throwable t) {
        if (!(t instanceof SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
                try {
                    out.clearBuffer();
                } catch (java.io.IOException e) {
                }
            if (_jspx_page_context != null)
                _jspx_page_context.handlePageException(t);
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:org.apache.struts.extras.SecureJakartaStreamMultiPartRequest.java

/**
 * Processes the FileItemStream as a Form Field.
 *
 * @param itemStream/*from   w  w w  . j a va2 s.c  o  m*/
 */
private void processFileItemStreamAsFormField(FileItemStream itemStream) {
    String fieldName = itemStream.getFieldName();
    try {
        List<String> values = null;
        String fieldValue = Streams.asString(itemStream.openStream());
        if (!parameters.containsKey(fieldName)) {
            values = new ArrayList<String>();
            parameters.put(fieldName, values);
        } else {
            values = parameters.get(fieldName);
        }
        values.add(fieldValue);
    } catch (IOException e) {
        e.printStackTrace();
        LOG.warn("Failed to handle form field '#0'.", fieldName);
    }
}

From source file:org.bimserver.servlets.UploadServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getHeader("Origin") != null
            && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin"))) {
        response.setStatus(403);/*from   w ww  .  j a  va2 s. c o m*/
        return;
    }
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");

    String token = (String) request.getSession().getAttribute("token");

    ObjectNode result = OBJECT_MAPPER.createObjectNode();
    response.setContentType("text/json");
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        long poid = -1;
        String comment = null;
        if (isMultipart) {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            InputStream in = null;
            String name = "";
            long deserializerOid = -1;
            boolean merge = false;
            boolean sync = false;
            String compression = null;
            String action = null;
            long topicId = -1;
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (item.isFormField()) {
                    if ("action".equals(item.getFieldName())) {
                        action = Streams.asString(item.openStream());
                    } else if ("token".equals(item.getFieldName())) {
                        token = Streams.asString(item.openStream());
                    } else if ("poid".equals(item.getFieldName())) {
                        poid = Long.parseLong(Streams.asString(item.openStream()));
                    } else if ("comment".equals(item.getFieldName())) {
                        comment = Streams.asString(item.openStream());
                    } else if ("topicId".equals(item.getFieldName())) {
                        topicId = Long.parseLong(Streams.asString(item.openStream()));
                    } else if ("sync".equals(item.getFieldName())) {
                        sync = Streams.asString(item.openStream()).equals("true");
                    } else if ("merge".equals(item.getFieldName())) {
                        merge = Streams.asString(item.openStream()).equals("true");
                    } else if ("compression".equals(item.getFieldName())) {
                        compression = Streams.asString(item.openStream());
                    } else if ("deserializerOid".equals(item.getFieldName())) {
                        deserializerOid = Long.parseLong(Streams.asString(item.openStream()));
                    }
                } else {
                    name = item.getName();
                    in = item.openStream();

                    if ("file".equals(action)) {
                        ServiceInterface serviceInterface = getBimServer().getServiceFactory()
                                .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                        SFile file = new SFile();
                        byte[] data = IOUtils.toByteArray(in);
                        file.setData(data);
                        file.setSize(data.length);
                        file.setFilename(name);
                        file.setMime(item.getContentType());
                        result.put("fileId", serviceInterface.uploadFile(file));
                    } else if (poid != -1) {
                        InputStream realStream = null;
                        if ("gzip".equals(compression)) {
                            realStream = new GZIPInputStream(in);
                        } else if ("deflate".equals(compression)) {
                            realStream = new InflaterInputStream(in);
                        } else {
                            realStream = in;
                        }
                        InputStreamDataSource inputStreamDataSource = new InputStreamDataSource(realStream);
                        inputStreamDataSource.setName(name);
                        DataHandler ifcFile = new DataHandler(inputStreamDataSource);

                        if (token != null) {
                            if (topicId == -1) {
                                ServiceInterface service = getBimServer().getServiceFactory()
                                        .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                                long newTopicId = service.checkin(poid, comment, deserializerOid, -1L, name,
                                        ifcFile, merge, sync);
                                result.put("topicId", newTopicId);
                            } else {
                                ServiceInterface service = getBimServer().getServiceFactory()
                                        .get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                                long newTopicId = service.checkinInitiated(topicId, poid, comment,
                                        deserializerOid, -1L, name, ifcFile, merge, true);
                                result.put("topicId", newTopicId);
                            }
                        }
                    } else {
                        result.put("exception", "No poid");
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("", e);
        sendException(response, e);
        return;
    }
    response.getWriter().write(result.toString());
}