Example usage for org.apache.commons.fileupload FileItem getContentType

List of usage examples for org.apache.commons.fileupload FileItem getContentType

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getContentType.

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:org.eclipse.che.api.factory.server.FactoryService.java

@POST
@Consumes(MULTIPART_FORM_DATA)//ww  w  . ja  v a  2 s  . c  om
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Create a new factory based on configuration and factory images", notes = "The field 'factory' is required")
@ApiResponses({ @ApiResponse(code = 200, message = "Factory successfully created"),
        @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
        @ApiResponse(code = 403, message = "The user does not have rights to create factory"),
        @ApiResponse(code = 409, message = "When factory with given name and creator already exists"),
        @ApiResponse(code = 500, message = "Internal server error occurred") })
public FactoryDto saveFactory(Iterator<FileItem> formData)
        throws ForbiddenException, ConflictException, BadRequestException, ServerException {
    try {
        final Set<FactoryImage> images = new HashSet<>();
        FactoryDto factory = null;
        while (formData.hasNext()) {
            final FileItem item = formData.next();
            switch (item.getFieldName()) {
            case ("factory"): {
                try (InputStream factoryData = item.getInputStream()) {
                    factory = factoryBuilder.build(factoryData);
                } catch (JsonSyntaxException ex) {
                    throw new BadRequestException("Invalid JSON value of the field 'factory' provided");
                }
                break;
            }
            case ("image"): {
                try (InputStream imageData = item.getInputStream()) {
                    final FactoryImage image = createImage(imageData, item.getContentType(),
                            NameGenerator.generate(null, 16));
                    if (image.hasContent()) {
                        images.add(image);
                    }
                }
                break;
            }
            default:
                //DO NOTHING
            }
        }
        requiredNotNull(factory, "factory configuration");
        processDefaults(factory);
        AddExecAgentInEnvironmentUtil.addExecAgent(factory.getWorkspace());
        createValidator.validateOnCreate(factory);
        return injectLinks(asDto(factoryManager.saveFactory(factory, images)), images);
    } catch (IOException ioEx) {
        throw new ServerException(ioEx.getLocalizedMessage(), ioEx);
    }
}

From source file:org.eclipse.che.api.vfs.server.VirtualFileSystemImpl.java

public static Response uploadFile(VirtualFile parent, Iterator<FileItem> formData)
        throws ForbiddenException, ConflictException, ServerException {
    try {/* www  . ja  v  a 2  s  . c  om*/
        FileItem contentItem = null;
        String mediaType = null;
        String name = null;
        boolean overwrite = false;

        while (formData.hasNext()) {
            FileItem item = formData.next();
            if (!item.isFormField()) {
                if (contentItem == null) {
                    contentItem = item;
                } else {
                    throw new ServerException("More then one upload file is found but only one should be. ");
                }
            } else if ("mimeType".equals(item.getFieldName())) {
                mediaType = item.getString().trim();
            } else if ("name".equals(item.getFieldName())) {
                name = item.getString().trim();
            } else if ("overwrite".equals(item.getFieldName())) {
                overwrite = Boolean.parseBoolean(item.getString().trim());
            }
        }

        if (contentItem == null) {
            throw new ServerException("Cannot find file for upload. ");
        }
        if (name == null || name.isEmpty()) {
            name = contentItem.getName();
        }
        if (mediaType == null || mediaType.isEmpty()) {
            mediaType = contentItem.getContentType();
        }

        if (mediaType != null) {
            final MediaType mediaTypeType = MediaType.valueOf(mediaType);
            mediaType = mediaTypeType.getType() + '/' + mediaTypeType.getSubtype();
        }

        try {
            try {
                parent.createFile(name, mediaType, contentItem.getInputStream());
            } catch (ConflictException e) {
                if (!overwrite) {
                    throw new ConflictException("Unable upload file. Item with the same name exists. ");
                }
                parent.getChild(name).updateContent(mediaType, contentItem.getInputStream(), null);
            }
        } catch (IOException ioe) {
            throw new ServerException(ioe.getMessage(), ioe);
        }

        return Response.ok("", MediaType.TEXT_HTML).build();
    } catch (ForbiddenException | ConflictException | ServerException e) {
        HtmlErrorFormatter.sendErrorAsHTML(e);
        // never thrown
        throw e;
    }
}

From source file:org.eclipse.che.api.workspace.server.stack.StackService.java

@POST
@Path("/{id}/icon")
@Consumes(MULTIPART_FORM_DATA)//from   w w  w.  j a v a2s.c om
@Produces(TEXT_PLAIN)
@GenerateLink(rel = LINK_REL_UPLOAD_ICON)
@ApiOperation(value = "Upload icon for required stack", notes = "This operation can be performed only by authorized stack owner")
@ApiResponses({ @ApiResponse(code = 200, message = "Image was successfully uploaded"),
        @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
        @ApiResponse(code = 403, message = "The user does not have access upload image for stack with required id"),
        @ApiResponse(code = 404, message = "The stack doesn't exist"),
        @ApiResponse(code = 500, message = "Internal server error occurred") })
public Response uploadIcon(@ApiParam("The image for stack") final Iterator<FileItem> formData,
        @ApiParam("The stack id") @PathParam("id") final String id)
        throws NotFoundException, ServerException, BadRequestException, ForbiddenException, ConflictException {
    if (formData.hasNext()) {
        FileItem fileItem = formData.next();
        StackIcon stackIcon = new StackIcon(fileItem.getName(), fileItem.getContentType(), fileItem.get());

        StackImpl stack = stackDao.getById(id);

        stack.setStackIcon(stackIcon);
        stackDao.update(stack);
    }
    return Response.ok().build();
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_commonsFileUpload() throws Exception {
    Servlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override/*from  w ww  .ja v  a  2  s.  c o m*/
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException, ServletException {

            boolean isMultipart = ServletFileUpload.isMultipartContent(req);
            Assert.assertTrue(isMultipart);

            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> items = null;
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> parseRequest = upload.parseRequest(req);
                items = parseRequest;
            } catch (FileUploadException e) {
                e.printStackTrace();
            }

            Assert.assertNotNull(items);
            Assert.assertFalse(items.isEmpty());

            FileItem fileItem = items.get(0);

            String submittedFileName = fileItem.getName();
            String contentType = fileItem.getContentType();
            long size = fileItem.getSize();

            PrintWriter writer = resp.getWriter();

            writer.write(submittedFileName);
            writer.write("|");
            writer.write(contentType);
            writer.write("|" + size);
        }
    };

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*");
    registrations.add(getBundleContext().registerService(Servlet.class, servlet, props));

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

    map.put("file", Arrays.<Object>asList(getClass().getResource("blue.png")));

    Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map);

    Assert.assertEquals("200", result.get("responseCode").get(0));
    Assert.assertEquals("blue.png|image/png|292", result.get("responseBody").get(0));
}

From source file:org.eclipse.kapua.app.console.servlet.FileServlet.java

@SuppressWarnings("unchecked")
public void parse(HttpServletRequest req) throws FileUploadException {
    s_logger.debug("upload.getFileSizeMax(): {}", getFileSizeMax());
    s_logger.debug("upload.getSizeMax(): {}", getSizeMax());

    // Parse the request
    List<FileItem> items = null;
    items = parseRequest(req);//from   w  w  w . j a va2 s .c  o m

    // Process the uploaded items
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();

            s_logger.debug("Form field item name: {}, value: {}", name, value);

            formFields.put(name, value);
        } else {
            String fieldName = item.getFieldName();
            String fileName = item.getName();
            String contentType = item.getContentType();
            boolean isInMemory = item.isInMemory();
            long sizeInBytes = item.getSize();

            s_logger.debug("File upload item name: {}, fileName: {}, contentType: {}, isInMemory: {}, size: {}",
                    new Object[] { fieldName, fileName, contentType, isInMemory, sizeInBytes });

            fileItems.add(item);
        }
    }
}

From source file:org.eclipse.kura.web.server.servlet.FileServlet.java

@SuppressWarnings("unchecked")
public void parse(HttpServletRequest req) throws FileUploadException {

    s_logger.debug("upload.getFileSizeMax(): {}", getFileSizeMax());
    s_logger.debug("upload.getSizeMax(): {}", getSizeMax());

    // Parse the request
    List<FileItem> items = null;
    items = parseRequest(req);//ww w  .j  a  v  a  2s.c om

    // Process the uploaded items
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();

            s_logger.debug("Form field item name: {}, value: {}", name, value);

            this.formFields.put(name, value);
        } else {
            String fieldName = item.getFieldName();
            String fileName = item.getName();
            String contentType = item.getContentType();
            boolean isInMemory = item.isInMemory();
            long sizeInBytes = item.getSize();

            s_logger.debug("File upload item name: {}, fileName: {}, contentType: {}, isInMemory: {}, size: {}",
                    new Object[] { fieldName, fileName, contentType, isInMemory, sizeInBytes });

            this.fileItems.add(item);
        }
    }
}

From source file:org.eclipse.lyo.oslc.am.resource.ResourceService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isFileUpload = ServletFileUpload.isMultipartContent(request);
    String contentType = request.getContentType();

    if (!isFileUpload && (RioStore.rdfFormatFromContentType(contentType) == null)) {
        throw new RioServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }//  ww w.  jav  a 2  s. c o  m

    InputStream content = request.getInputStream();

    if (isFileUpload) {
        // being uploaded from a web page
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);

            // find the first (and only) file resource in the post
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    // this is a form field, maybe we can accept a title or descr?
                } else {
                    content = item.getInputStream();
                    contentType = item.getContentType();
                }
            }

        } catch (Exception e) {
            throw new RioServiceException(e);
        }
    }

    RioStore store = this.getStore();
    if (RioStore.rdfFormatFromContentType(contentType) != null) {
        try {
            String resUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(resUri);
            List<RioStatement> statements = store.parse(resUri, content, contentType);
            resource.addStatements(statements);
            String userUri = getUserUri(request.getRemoteUser());

            // if it parsed, then add it to the store.
            store.update(resource, userUri);

            // now get it back, to find 
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }
    } else if (IAmConstants.CT_APP_X_VND_MSPPT.equals(contentType) || isFileUpload) {
        try {

            ByteArrayInputStream bais = isToBais(content);

            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(uri);
            resource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
            resource.addRdfType(IAmConstants.RIO_AM_PPT_DECK);
            String id = resource.getIdentifier();
            String deckTitle = "PPT Deck " + id;
            resource.setTitle(deckTitle);
            resource.setDescription("A Power Point Deck");
            String sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());

            store.storeBinaryResource(bais, id);
            bais.reset();

            SlideShow ppt = new SlideShow(bais);
            Dimension pgsize = ppt.getPageSize();

            Slide[] slide = ppt.getSlides();
            for (int i = 0; i < slide.length; i++) {
                String slideTitle = extractTitle(slide[i]);
                String slideUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
                Resource slideResource = new Resource(slideUri);
                slideResource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
                slideResource.addRdfType(IAmConstants.RIO_AM_PPT_SLIDE);
                String slideId = slideResource.getIdentifier();
                slideResource.setTitle(slideTitle);
                sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + slideId;
                slideResource.setSource(sourceUri);
                slideResource.setSourceContentType(IConstants.CT_IMAGE_PNG);
                store.update(slideResource, userUri);

                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide[i].draw(graphics);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                javax.imageio.ImageIO.write(img, "png", out);
                ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray());
                store.storeBinaryResource(is, slideId);
                out.close();
                is.close();
                try {
                    RioValue v = new RioValue(RioValueType.URI, slideResource.getUri());
                    resource.appendToSeq(IConstants.RIO_NAMESPACE + "slides", v);
                } catch (UnrecognizedValueTypeException e) {
                    // log this?  don't want to throw away everything, since this should never happen
                }
            }

            store.update(resource, userUri);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }

    } else {
        // must be a binary or unknown format, treat as black box
        // normally a service provider will understand this and parse it appropriately
        // however this server will accept any blank box resource

        try {
            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(uri);
            String id = resource.getIdentifier();
            resource.setTitle("Resource " + id);
            resource.setDescription("A binary resource");
            String sourceUri = getBaseUrl() + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());
            store.update(resource, userUri);

            store.storeBinaryResource(content, id);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }
    }
}

From source file:org.eclipse.lyo.samples.sharepoint.adapter.ResourceService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("entered do Post for /resource");
    boolean isFileUpload = ServletFileUpload.isMultipartContent(request);
    String contentType = request.getContentType();

    if (!isFileUpload && !IConstants.CT_RDF_XML.equals(contentType)) {
        throw new ShareServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }//from   w  w w  .  j  a  v  a2  s.c o  m

    InputStream content = request.getInputStream();

    if (isFileUpload) {
        // being uploaded from a web page
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);

            // find the first (and only) file resource in the post
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    // this is a form field, maybe we can accept a title or descr?
                } else {
                    content = item.getInputStream();
                    contentType = item.getContentType();
                }
            }

        } catch (Exception e) {
            throw new ShareServiceException(e);
        }
    }

    ShareStore store = this.getStore();
    if (ShareStore.rdfFormatFromContentType(contentType) != null) {
        try {
            String resUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            SharepointResource resource = new SharepointResource(resUri);
            List<ShareStatement> statements = store.parse(resUri, content, contentType);
            resource.addStatements(statements);
            String userUri = getUserUri(request.getRemoteUser());

            // if it parsed, then add it to the store.
            store.update(resource, userUri);

            // now get it back, to find 
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }
    } else if (IAmConstants.CT_APP_X_VND_MSPPT.equals(contentType) || isFileUpload) {
        try {

            ByteArrayInputStream bais = isToBais(content);

            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            SharepointResource resource = new SharepointResource(uri);
            resource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
            resource.addRdfType(IAmConstants.RIO_AM_PPT_DECK);
            String id = resource.getIdentifier();
            String deckTitle = "PPT Deck " + id;
            resource.setTitle(deckTitle);
            resource.setDescription("A Power Point Deck");
            String sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());

            store.storeBinaryResource(bais, id);
            bais.reset();

            SlideShow ppt = new SlideShow(bais);
            Dimension pgsize = ppt.getPageSize();

            Slide[] slide = ppt.getSlides();
            for (int i = 0; i < slide.length; i++) {
                String slideTitle = extractTitle(slide[i]);
                String slideUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
                SharepointResource slideResource = new SharepointResource(slideUri);
                slideResource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
                slideResource.addRdfType(IAmConstants.RIO_AM_PPT_SLIDE);
                String slideId = slideResource.getIdentifier();
                slideResource.setTitle(slideTitle);
                sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + slideId;
                slideResource.setSource(sourceUri);
                slideResource.setSourceContentType(IConstants.CT_IMAGE_PNG);
                store.update(slideResource, userUri);

                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide[i].draw(graphics);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                javax.imageio.ImageIO.write(img, "png", out);
                ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray());
                store.storeBinaryResource(is, slideId);
                out.close();
                is.close();
                try {
                    ShareValue v = new ShareValue(ShareValueType.URI, slideResource.getUri());
                    resource.appendToSeq(IConstants.SHARE_NAMESPACE + "slides", v);
                } catch (UnrecognizedValueTypeException e) {
                    // log this?  don't want to throw away everything, since this should never happen
                }
            }

            store.update(resource, userUri);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }

    } else {
        // must be a binary or unknown format, treat as black box
        // normally a service provider will understand this and parse it appropriately
        // however this server will accept any blank box resource

        try {
            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            SharepointResource resource = new SharepointResource(uri);
            String id = resource.getIdentifier();
            resource.setTitle("Resource " + id);
            resource.setDescription("A binary resource");
            String sourceUri = getBaseUrl() + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());
            store.update(resource, userUri);

            store.storeBinaryResource(content, id);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }
    }
}

From source file:org.eclipse.lyo.samples.sharepoint.SharepointConnector.java

public int createDocument(HttpServletResponse response, String library, FileItem item)
        throws UnrecognizedValueTypeException, ShareServerException {
    //   System.out.println("createDocument: uri='" + uri + "'");
    //SharepointResource sharepointResource = new SharepointResource(uri);

    //       String filename = resource.getSource();
    //       //from  w  w  w. j  a v  a  2 s  .c om
    //      OEntity newProduct = odatac.createEntity("Empire").properties(OProperties.int32("Id", 10))
    //                                                       .properties(OProperties.string("Name", filename))
    //                                                       .properties(OProperties.string("ContentType","Document"))
    //                                                       .properties(OProperties.string("Title","Architecture"))
    //                                                       .properties(OProperties.string("ApprovalStatus","2"))
    //                                                       .properties(OProperties.string("Path","/Empire"))   
    //                                                         .execute();  

    // no obvious API in odata4j to create a document, default apache http Create
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");

    BufferedReader br = null;
    int returnCode = 500;
    PostMethod method = null;
    try {
        client.setConnectionTimeout(8000);

        method = new PostMethod(SharepointInitializer.getSharepointUri() + "/" + library);
        String userPassword = SharepointInitializer.getUsername() + ":" + SharepointInitializer.getPassword();
        String encoding = Base64.encodeBase64String(userPassword.getBytes());
        encoding = encoding.replaceAll("\r\n?", "");
        method.setRequestHeader("Authorization", "Basic " + encoding);
        method.addRequestHeader("Content-type", item.getContentType());
        method.addRequestHeader(IConstants.HDR_SLUG, "/" + library + "/" + item.getName());

        //InputStream is =  new FileInputStream("E:\\odata\\sharepoint\\DeathStarTest.doc");

        RequestEntity entity = new InputStreamRequestEntity(item.getInputStream(), "application/msword");
        method.setRequestEntity(entity);
        method.setDoAuthentication(true);

        returnCode = client.executeMethod(method);

        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.err.println("The Post method is not implemented by this URI");
            // still consume the response body
            method.getResponseBodyAsString();
        } else {
            //br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            InputStream is = method.getResponseBodyAsStream();
            //br = new BufferedReader(new InputStreamReader(is));          
            //    String readLine;
            //    while(((readLine = br.readLine()) != null)) {
            //      System.out.println(readLine);
            //    }

            response.setContentType("text/html");
            //response.setContentType("application/atom+xml");
            //response.setContentLength(is.getBytes().length);
            response.setStatus(IConstants.SC_OK);
            //response.getWriter().write("<html><head><title>hello world</title></head><body><p>hello world!</p></body></html>");
            //response.getWriter().write(method.getResponseBodyAsString());

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder parser = factory.newDocumentBuilder();
            Document doc = parser.parse(is);
            Element root = doc.getDocumentElement();

            System.out.println("Root element of the doc is " + root.getNodeName());

            //         String msftdPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            //         String msftmPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

            String id = null;
            String name = null;
            NodeList nl = root.getElementsByTagName("d:Id");
            if (nl.getLength() > 0) {
                id = nl.item(0).getFirstChild().getNodeValue();
            }

            //nl = root.getElementsByTagName("d:ContentType");         
            //if (nl.getLength() > 0) {
            //   type = nl.item(0).getFirstChild().getNodeValue(); 
            //}

            nl = root.getElementsByTagName("d:Name");
            if (nl.getLength() > 0) {
                name = nl.item(0).getFirstChild().getNodeValue();
            }

            response.getWriter().write("<html>");
            response.getWriter().write("<head>");
            response.getWriter().write("</head>");
            response.getWriter().write("<body>");
            response.getWriter().write("<p>" + name + " was created with an Id =" + id + "</p>");
            response.getWriter().write("</body>");
            response.getWriter().write("</html>");

            //response.getWriter().write(is.content);
            //String readLine;
            //while(((readLine = br.readLine()) != null)) {
            //   response.getWriter().write(readLine);
            //}
            //response.setContentType(IConstants.CT_XML);
            //response.getWriter().write(is.toString()); 
            //response.setStatus(IConstants.SC_OK);
            //test 
            //   String readLine;
            //   while(((readLine = br.readLine()) != null)) {
            //     System.out.println(readLine);
            //   }
        }
    } catch (Exception e) {
        System.err.println(e);
        e.printStackTrace();
    } finally {
        if (method != null)
            method.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
            }
    }
    return returnCode;
}

From source file:org.eclipse.rwt.widgets.upload.servlet.FileUploadServiceHandler.java

/**
 * Treats the request as a post request which contains the file to be
 * uploaded. Uses the apache commons fileupload library to
 * extract the file from the request, attaches a {@link FileUploadListener} to 
 * get notified about the progress and writes the file content
 * to the given {@link FileUploadStorageItem}
 * @param request Request object, must not be null
 * @param fileUploadStorageitem Object where the file content is set to.
 * If null, nothing happens./*  w  w w  .java  2  s.  com*/
 * @param uploadProcessId Each upload action has a unique process identifier to
 * match subsequent polling calls to get the progress correctly to the uploaded file.
 *
 */
private void handleFileUpload(final HttpServletRequest request,
        final FileUploadStorageItem fileUploadStorageitem, final String uploadProcessId) {
    // Ignore upload requests which have no valid widgetId
    if (fileUploadStorageitem != null && uploadProcessId != null && !"".equals(uploadProcessId)) {

        // Create file upload factory and upload servlet
        // You could use new DiskFileItemFactory(threshold, location)
        // to configure a custom in-memory threshold and storage location.
        // By default the upload files are stored in the java.io.tmpdir
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Create a file upload progress listener
        final ProgressListener listener = new ProgressListener() {

            public void update(final long aBytesRead, final long aContentLength, final int anItem) {
                fileUploadStorageitem.updateProgress(aBytesRead, aContentLength);
            }

        };
        // Upload servlet allows to set upload listener
        upload.setProgressListener(listener);
        fileUploadStorageitem.setUploadProcessId(uploadProcessId);

        FileItem fileItem = null;
        try {
            final List uploadedItems = upload.parseRequest(request);
            // Only one file upload at once is supported. If there are multiple files, take
            // the first one and ignore other
            if (uploadedItems.size() > 0) {
                fileItem = (FileItem) uploadedItems.get(0);
                // Don't check for file size 0 because this prevents uploading new empty office xp documents
                // which have a file size of 0.
                if (!fileItem.isFormField()) {
                    fileUploadStorageitem.setFileInputStream(fileItem.getInputStream());
                    fileUploadStorageitem.setContentType(fileItem.getContentType());
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}