Example usage for javax.servlet MultipartConfigElement MultipartConfigElement

List of usage examples for javax.servlet MultipartConfigElement MultipartConfigElement

Introduction

In this page you can find the example usage for javax.servlet MultipartConfigElement MultipartConfigElement.

Prototype

public MultipartConfigElement(MultipartConfig annotation) 

Source Link

Document

Constructs an instance from a MultipartConfig annotation value.

Usage

From source file:io.lavagna.config.DispatcherServletInitializer.java

@Override
protected void customizeRegistration(Dynamic registration) {

    MultipartConfigElement multipartConfigElement = new MultipartConfigElement("");

    registration.setMultipartConfig(multipartConfigElement);
    registration.setInitParameter("dispatchOptionsRequest", "true");
    registration.setAsyncSupported(true);
}

From source file:org.fejoa.server.Portal.java

@Override
public void handle(String s, Request request, HttpServletRequest httpServletRequest,
        HttpServletResponse response) throws IOException, ServletException {
    response.setContentType("text/plain;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    request.setHandled(true);//  w ww.  j a  v  a2  s  .c  o  m

    final MultipartConfigElement MULTI_PART_CONFIG = new MultipartConfigElement(
            System.getProperty("java.io.tmpdir"));
    if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")) {
        request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);
    }

    Session session = new Session(baseDir, httpServletRequest.getSession());
    ResponseHandler responseHandler = new ResponseHandler(response);

    Part messagePart = request.getPart(HTMLRequest.MESSAGE_KEY);
    Part data = request.getPart(HTMLRequest.DATA_KEY);

    if (messagePart == null) {
        responseHandler.setResponseHeader("empty request!");
        responseHandler.finish();
        return;
    }

    StringWriter stringWriter = new StringWriter();
    StreamHelper.copy(messagePart.getInputStream(), stringWriter);

    String error = handleJson(responseHandler, stringWriter.toString(),
            (data != null) ? data.getInputStream() : null, session);

    if (!responseHandler.isHandled() || error != null)
        responseHandler.setResponseHeader(error);

    responseHandler.finish();
}

From source file:org.bonitasoft.web.designer.SpringWebApplicationInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {

    for (String line : BANNER) {
        logger.info(line);//from  w  w w.  jav a  2 s. co m
    }
    logger.info(Strings.repeat("=", 100));
    logger.info(String.format("UI-DESIGNER : %s edition v.%s", prop.getProperty("designer.edition"),
            prop.getProperty("designer.version")));
    logger.info(Strings.repeat("=", 100));

    // Create the root context Spring
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(new Class<?>[] { ApplicationConfig.class });

    // Manage the lifecycle of the root application context
    servletContext.addListener(new ContextLoaderListener(rootContext));

    // Register and map the dispatcher servlet
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(rootContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.setMultipartConfig(new MultipartConfigElement(System.getProperty("java.io.tmpdir")));
    dispatcher.setAsyncSupported(true);
    dispatcher.addMapping("/");
}

From source file:com.groupon.odo.controllers.HomeController.java

@Bean
MultipartConfigElement multipartConfigElement() {
    return new MultipartConfigElement("");
}

From source file:de.thischwa.pmcms.server.JettyLauncher.java

@Override
public void onApplicationStart() {
    File dataDir = new File(dataDirStr);
    String applicationPath = Constants.APPLICATION_DIR.getAbsolutePath().replace('\\', '/');
    if (!applicationPath.endsWith("/"))
        applicationPath += "/";
    try {/*from   w  w  w.  j  a  v  a 2  s .  c  o  m*/
        ClassLoader classLoader = ClassUtils.getDefaultClassLoader(); // spring class loader
        server = new Server();
        ServerConnector connector = new ServerConnector(server);
        connector.setHost(host);
        connector.setPort(Integer.parseInt(port));
        connector.setIdleTimeout(Integer.MAX_VALUE);
        server.addConnector(connector);

        ServletContextHandler contextDataDir = new ServletContextHandler(server, "/",
                ServletContextHandler.NO_SECURITY);
        contextDataDir.setClassLoader(classLoader);
        contextDataDir.setResourceBase(dataDir.getAbsolutePath());
        contextDataDir.setAttribute(ServletContext.TEMPDIR, new File(System.getProperty("java.io.tmpdir")));

        ServletHolder holderDefaults = new ServletHolder(ResourceServlet.class);
        holderDefaults.setInitParameter("basePath", "defaults");
        holderDefaults.setInitParameter("aliases", "false");
        contextDataDir.addServlet(holderDefaults, "/defaults/*");

        ServletHolder holderHelp = new ServletHolder(ResourceServlet.class);
        holderHelp.setInitParameter("basePath", "help");
        holderHelp.setInitParameter("aliases", "false");
        contextDataDir.addServlet(holderHelp, "/help/*");

        ServletHolder holderFilemanger = new ServletHolder(ResourceServlet.class);
        holderFilemanger.setInitParameter("basePath",
                new File(Constants.APPLICATION_DIR, "filemanager").getAbsolutePath());
        contextDataDir.addServlet(holderFilemanger, "/filemanager/*");

        contextDataDir.addServlet(buildLoadOnStart(EditorServlet.class),
                "/" + Constants.LINK_IDENTICATOR_EDIT + "/*");
        contextDataDir.addServlet(buildLoadOnStart(ContentSaverServlet.class),
                "/" + Constants.LINK_IDENTICATOR_SAVE + "/*");
        contextDataDir.addServlet(buildLoadOnStart(PreviewServlet.class),
                "/" + Constants.LINK_IDENTICATOR_PREVIEW + "/*");

        ServletHolder holderConnector = new ServletHolder(ConnectorServlet.class);
        holderConnector.setInitOrder(2);
        holderConnector.getRegistration()
                .setMultipartConfig(new MultipartConfigElement(Constants.TEMP_DIR.getAbsolutePath()));
        contextDataDir.addServlet(holderConnector, "/filemanager/connectors/java/*");
        contextDataDir.addServlet(holderConnector, "/filemanager/scripts/filemanager.config.js");

        ServletHolder holderCodeMirror = new ServletHolder(ZipProxyServlet.class);
        holderCodeMirror.setInitParameter("file", "sourceeditor/codemirror-3.22.zip");
        holderCodeMirror.setInitParameter("zipPathToSkip", "codemirror-3.22");
        contextDataDir.addServlet(holderCodeMirror, "/codemirror/*");

        ServletHolder holderSiteResource = new ServletHolder(SiteResourceServlet.class);
        holderSiteResource.setInitParameter("basePath", new File(dataDir, sitesDir).getAbsolutePath());
        contextDataDir.addServlet(holderSiteResource,
                String.format("/%s/*", Constants.LINK_IDENTICATOR_SITE_RESOURCE));

        //         ServletHolder holderCKEditor = new ServletHolder(ZipProxyServlet.class);
        //         holderCKEditor.setInitParameter("file", "ckeditor_4.3.3_full.zip");
        //         holderCKEditor.setInitParameter("zipPathToSkip", "ckeditor");
        //         contextDataDir.addServlet(holderCKEditor, "/ckeditor/*");
        ServletHolder holderCKEditor = new ServletHolder(ResourceServlet.class);
        holderCKEditor.setInitParameter("basePath", "ckeditor");
        contextDataDir.addServlet(holderCKEditor, "/ckeditor/*");

        ServletHolder holderTest = new ServletHolder(TestServlet.class);
        contextDataDir.addServlet(holderTest, "/webgui/*");

        ServletHolder holderResourceWebgui = new ServletHolder(ResourceServlet.class);
        holderResourceWebgui.setInitParameter("basePath",
                Constants.APPLICATION_DIR.getAbsolutePath() + "/webgui/resources");
        contextDataDir.addServlet(holderResourceWebgui, "/resc/*");

        server.start();
    } catch (Exception e) {
        throw new RuntimeException("Start of jetty failed: " + e.getMessage(), e);
    }
    super.onApplicationStart();
}

From source file:org.codice.ddf.catalog.ui.catalog.CatalogApplication.java

@Override
public void init() {
    head("/catalog/", (req, res) -> {
        LOGGER.trace("Ping!");
        res.status(HttpStatus.SC_OK);/*from  w  w w. j av  a2 s.  co  m*/
        return res;
    });

    head(CATALOG_ID_PATH, (req, res) -> getHeaders(req, res, null, req.params(":id")));

    head("/catalog/sources/:sourceid/:id",
            (req, res) -> getHeaders(req, res, req.params(":sourceid"), req.params(":id")));

    get("/catalog/sources", (req, res) -> {
        final BinaryContent content = catalogService.getSourcesInfo();

        try (InputStream inputStream = content.getInputStream()) {
            res.status(HttpStatus.SC_OK);
            res.body(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
            res.type(content.getMimeTypeValue());
        }

        // Add the Accept-ranges header to let the client know that we accept ranges in bytes
        res.header(HEADER_ACCEPT_RANGES, BYTES);
        return res;
    });

    get(CATALOG_ID_PATH,
            (req, res) -> getDocument(req, res, null, req.params(":id"), req.queryParams(TRANSFORM)));

    get("/catalog/sources/:sourceid/:id", (req, res) -> getDocument(req, res, req.params(":sourceid"),
            req.params(":id"), req.queryParams(TRANSFORM)));

    post("/catalog/metacard", (req, res) -> {
        try {
            final BinaryContent content = catalogService.createMetacard(req.raw(), req.queryParams(TRANSFORM));

            try (InputStream inputStream = content.getInputStream()) {
                res.status(HttpStatus.SC_OK);
                res.body(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
                res.type(content.getMimeTypeValue());
            }

            return res;
        } catch (CatalogServiceException e) {
            return createBadRequestResponse(res, e.getMessage());
        }
    });

    post("/catalog/", (req, res) -> {
        if (req.contentType().startsWith("multipart/")) {
            req.attribute(ECLIPSE_MULTIPART_CONFIG,
                    new MultipartConfigElement(System.getProperty(JAVA_IO_TMPDIR)));

            return addDocument(res, req.raw().getRequestURL(), req.contentType(), req.queryParams(TRANSFORM),
                    req.raw(), new ByteArrayInputStream(req.bodyAsBytes()));
        }

        if (req.contentType().startsWith("text/") || req.contentType().startsWith("application/")) {
            return addDocument(res, req.raw().getRequestURL(), req.contentType(), req.queryParams(TRANSFORM),
                    null, new ByteArrayInputStream(req.bodyAsBytes()));
        }

        res.status(HttpStatus.SC_NOT_FOUND);
        return res;
    });

    put(CATALOG_ID_PATH, (req, res) -> {
        if (req.contentType().startsWith("multipart/")) {
            req.attribute(ECLIPSE_MULTIPART_CONFIG,
                    new MultipartConfigElement(System.getProperty(JAVA_IO_TMPDIR)));

            return updateDocument(res, req.params(":id"), req.contentType(), req.queryParams(TRANSFORM),
                    req.raw(), new ByteArrayInputStream(req.bodyAsBytes()));
        }

        if (req.contentType().startsWith("text/") || req.contentType().startsWith("application/")) {
            return updateDocument(res, req.params(":id"), req.contentType(), req.queryParams(TRANSFORM), null,
                    new ByteArrayInputStream(req.bodyAsBytes()));
        }

        res.status(HttpStatus.SC_NOT_FOUND);
        return res;
    });

    delete(CATALOG_ID_PATH, (req, res) -> {
        try {
            String id = req.params(":id");
            catalogService.deleteDocument(id);
            res.status(HttpStatus.SC_OK);
            return id;

        } catch (CatalogServiceException e) {
            return createBadRequestResponse(res, e.getMessage());
        }
    });
}

From source file:com.galenframework.storage.controllers.api.PageApiController.java

private FileInfo copyImageToStorage(Request req) throws IOException, ServletException {
    if (req.raw().getAttribute("org.eclipse.jetty.multipartConfig") == null) {
        MultipartConfigElement multipartConfigElement = new MultipartConfigElement(
                System.getProperty("java.io.tmpdir"));
        req.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement);
    }/*w ww.  j a  v a2  s .c o m*/

    Part file = req.raw().getPart("file");
    FileInfo imageInfo = fileStorage.saveImageToStorage(file.getInputStream());
    file.delete();
    return imageInfo;
}

From source file:org.ireland.jnetty.dispatch.servlet.ServletConfigImpl.java

public MultipartConfigElement getMultipartConfig() {
    if (_multipartConfigElement == null) {
        Class<?> servletClass = null;

        try {//from w w w . j  av  a2s  .c  o m
            servletClass = getServletClass();
        } catch (Exception e) {
            log.debug(e.toString(), e);
        }

        if (servletClass != null) {
            MultipartConfig config = (MultipartConfig) servletClass.getAnnotation(MultipartConfig.class);

            if (config != null)
                _multipartConfigElement = new MultipartConfigElement(config);
        }
    }

    return _multipartConfigElement;
}

From source file:com.jsmartframework.web.manager.ContextControl.java

@Override
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    try {//from   w  w  w.j  ava  2  s  . c o m
        ServletContext servletContext = event.getServletContext();

        CONFIG.init(servletContext);
        if (CONFIG.getContent() == null) {
            throw new RuntimeException("Configuration file " + Constants.WEB_CONFIG_XML
                    + " was not found in WEB-INF resources folder!");
        }

        String contextConfigLocation = "com.jsmartframework.web.manager";
        if (CONFIG.getContent().getPackageScan() != null) {
            contextConfigLocation += "," + CONFIG.getContent().getPackageScan();
        }

        // Configure necessary parameters in the ServletContext to set Spring configuration without needing an XML file
        AnnotationConfigWebApplicationContext configWebAppContext = new AnnotationConfigWebApplicationContext();
        configWebAppContext.setConfigLocation(contextConfigLocation);

        CONTEXT_LOADER = new ContextLoader(configWebAppContext);
        CONTEXT_LOADER.initWebApplicationContext(servletContext);

        TagEncrypter.init();
        TEXTS.init();
        IMAGES.init(servletContext);
        HANDLER.init(servletContext);

        // ServletControl -> @MultipartConfig @WebServlet(name = "ServletControl", displayName = "ServletControl", loadOnStartup = 1)
        Servlet servletControl = servletContext.createServlet(
                (Class<? extends Servlet>) Class.forName("com.jsmartframework.web.manager.ServletControl"));
        ServletRegistration.Dynamic servletControlReg = (ServletRegistration.Dynamic) servletContext
                .addServlet("ServletControl", servletControl);
        servletControlReg.setAsyncSupported(true);
        servletControlReg.setLoadOnStartup(1);

        // ServletControl Initial Parameters
        InitParam[] initParams = CONFIG.getContent().getInitParams();
        if (initParams != null) {
            for (InitParam initParam : initParams) {
                servletControlReg.setInitParameter(initParam.getName(), initParam.getValue());
            }
        }

        // MultiPart to allow file upload on ServletControl
        MultipartConfigElement multipartElement = getServletMultipartElement();
        if (multipartElement != null) {
            servletControlReg.setMultipartConfig(multipartElement);
        }

        // Security constraint to ServletControl
        ServletSecurityElement servletSecurityElement = getServletSecurityElement(servletContext);
        if (servletSecurityElement != null) {
            servletControlReg.setServletSecurity(servletSecurityElement);
        }

        // TODO: Fix problem related to authentication by container to use SSL dynamically (Maybe create more than one servlet for secure and non-secure patterns)
        // Check also the use of request.login(user, pswd)
        // Check the HttpServletRequest.BASIC_AUTH, CLIENT_CERT_AUTH, FORM_AUTH, DIGEST_AUTH
        // servletReg.setRunAsRole("admin");
        // servletContext.declareRoles("admin");

        // ServletControl URL mapping
        String[] servletMapping = getServletMapping();
        servletControlReg.addMapping(servletMapping);

        // ErrorFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter errorFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.ErrorFilter"));
        FilterRegistration.Dynamic errorFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("ErrorFilter", errorFilter);

        errorFilterReg.setAsyncSupported(true);
        errorFilterReg.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR), true, "/*");

        // EncodeFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter encodeFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.EncodeFilter"));
        FilterRegistration.Dynamic encodeFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("EncodeFilter", encodeFilter);

        encodeFilterReg.setAsyncSupported(true);
        encodeFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // CacheFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter cacheFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.CacheFilter"));
        FilterRegistration.Dynamic cacheFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("CacheFilter", cacheFilter);

        cacheFilterReg.setAsyncSupported(true);
        cacheFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // Add custom filters defined by client
        for (String filterName : sortCustomFilters()) {
            Filter customFilter = servletContext
                    .createFilter((Class<? extends Filter>) HANDLER.webFilters.get(filterName));
            HANDLER.executeInjection(customFilter);

            WebFilter webFilter = customFilter.getClass().getAnnotation(WebFilter.class);
            FilterRegistration.Dynamic customFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter(filterName, customFilter);

            if (webFilter.initParams() != null) {
                for (WebInitParam initParam : webFilter.initParams()) {
                    customFilterReg.setInitParameter(initParam.name(), initParam.value());
                }
            }
            customFilterReg.setAsyncSupported(webFilter.asyncSupported());
            customFilterReg.addMappingForUrlPatterns(EnumSet.copyOf(Arrays.asList(webFilter.dispatcherTypes())),
                    true, webFilter.urlPatterns());
        }

        // FilterControl -> @WebFilter(servletNames = {"ServletControl"})
        Filter filterControl = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.FilterControl"));
        FilterRegistration.Dynamic filterControlReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("FilterControl", filterControl);

        filterControlReg.setAsyncSupported(true);
        filterControlReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // OutputFilter -> @WebFilter(servletNames = {"ServletControl"})
        Filter outputFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.OutputFilter"));
        FilterRegistration.Dynamic outputFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("OutputFilter", outputFilter);

        outputFilterReg.setAsyncSupported(true);
        outputFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // AsyncFilter -> @WebFilter(servletNames = {"ServletControl"})
        // Filter used case AsyncContext is dispatched internally by AsyncBean implementation
        Filter asyncFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.AsyncFilter"));
        FilterRegistration.Dynamic asyncFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("AsyncFilter", asyncFilter);

        asyncFilterReg.setAsyncSupported(true);
        asyncFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.ASYNC), true, "ServletControl");

        // SessionControl -> @WebListener
        EventListener sessionListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.SessionControl"));
        servletContext.addListener(sessionListener);

        // RequestControl -> @WebListener
        EventListener requestListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.RequestControl"));
        servletContext.addListener(requestListener);

        // Custom WebServlet -> Custom Servlets created by application
        for (String servletName : HANDLER.webServlets.keySet()) {
            Servlet customServlet = servletContext
                    .createServlet((Class<? extends Servlet>) HANDLER.webServlets.get(servletName));
            HANDLER.executeInjection(customServlet);

            WebServlet webServlet = customServlet.getClass().getAnnotation(WebServlet.class);
            ServletRegistration.Dynamic customReg = (ServletRegistration.Dynamic) servletContext
                    .addServlet(servletName, customServlet);

            customReg.setLoadOnStartup(webServlet.loadOnStartup());
            customReg.setAsyncSupported(webServlet.asyncSupported());

            WebInitParam[] customInitParams = webServlet.initParams();
            if (customInitParams != null) {
                for (WebInitParam customInitParam : customInitParams) {
                    customReg.setInitParameter(customInitParam.name(), customInitParam.value());
                }
            }

            // Add mapping url for custom servlet
            customReg.addMapping(webServlet.urlPatterns());

            if (customServlet.getClass().isAnnotationPresent(MultipartConfig.class)) {
                customReg.setMultipartConfig(new MultipartConfigElement(
                        customServlet.getClass().getAnnotation(MultipartConfig.class)));
            }
        }

        // Controller Dispatcher for Spring MVC
        Set<String> requestPaths = HANDLER.requestPaths.keySet();
        if (!requestPaths.isEmpty()) {
            ServletRegistration.Dynamic mvcDispatcherReg = servletContext.addServlet("DispatcherServlet",
                    new DispatcherServlet(configWebAppContext));
            mvcDispatcherReg.setLoadOnStartup(1);
            mvcDispatcherReg.addMapping(requestPaths.toArray(new String[requestPaths.size()]));

            // RequestPathFilter -> @WebFilter(servletNames = {"DispatcherServlet"})
            Filter requestPathFilter = servletContext.createFilter((Class<? extends Filter>) Class
                    .forName("com.jsmartframework.web.manager.RequestPathFilter"));
            FilterRegistration.Dynamic reqPathFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter("RequestPathFilter", requestPathFilter);

            reqPathFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST,
                    DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.INCLUDE, DispatcherType.ASYNC),
                    true, "DispatcherServlet");
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.jsmartframework.web.manager.ContextControl.java

private MultipartConfigElement getServletMultipartElement() {
    UploadConfig uploadConfig = null;//w w  w.ja  v  a2  s.  c o m
    MultipartConfigElement multipartElement = new MultipartConfigElement("");

    if ((uploadConfig = CONFIG.getContent().getUploadConfig()) != null) {
        multipartElement = new MultipartConfigElement(uploadConfig.getLocation(), uploadConfig.getMaxFileSize(),
                uploadConfig.getMaxRequestSize(), uploadConfig.getFileSizeThreshold());
    }

    return multipartElement;
}