Example usage for javax.servlet ServletContext TEMPDIR

List of usage examples for javax.servlet ServletContext TEMPDIR

Introduction

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

Prototype

String TEMPDIR

To view the source code for javax.servlet ServletContext TEMPDIR.

Click Source Link

Document

The name of the ServletContext attribute which stores the private temporary directory (of type java.io.File) provided by the servlet container for the ServletContext

Usage

From source file:cn.edu.zjnu.acm.judge.config.StartUpConfiguration.java

@Autowired
public void setStartUpDate(ServletContext servlet, ApplicationContext application) {
    servlet.setAttribute("startUpDate", application.getStartupDate());
    log.debug("{}: {}", ServletContext.TEMPDIR, servlet.getAttribute(ServletContext.TEMPDIR));
}

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  ww .j  a  va 2s  . 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:com.origami.sgm.services.ejbs.censocat.FotosServlet.java

protected void genFactory() {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    if (this.getServletConfig() != null && this.getServletConfig().getServletContext() != null) {
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute(ServletContext.TEMPDIR);
        factory.setRepository(repository);
        uploadFotoBean.setFactory(factory);
    }//  w  ww .  java 2  s .c om
}

From source file:codes.thischwa.c5c.UserObjectProxy.java

/**
 * Instantiates all user-objects./*from ww  w  . ja v  a2s  . c  om*/
 *
 * @param servletContext
 *            the servlet context
 * @throws RuntimeException
 *             is thrown, if one of the required user-objects couldn't be instantiated
 */
static void init(ServletContext servletContext) throws RuntimeException {
    UserObjectProxy.servletContext = servletContext;

    // try to instantiate to FileCapacity
    String className = PropertiesLoader.getFileCapabilityImpl();
    if (StringUtils.isNullOrEmpty(className))
        throw new RuntimeException(
                "Empty FilemanagerCapability implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        fileCapability = (FilemanagerCapability) clazz.newInstance();
        logger.info("FilemanagerCapability initialized to {}", className);
    } catch (Throwable e) {
        String msg = String.format("FilemanagerCapability implementation [%s] couldn't be instantiated.",
                className);
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to initialize the MessageResolver
    className = PropertiesLoader.getMessageResolverImpl();
    if (StringUtils.isNullOrEmpty(className))
        throw new RuntimeException(
                "Empty MessageResolver implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        messageHolder = (MessageResolver) clazz.newInstance();
        messageHolder.setServletContext(servletContext);
        logger.info("MessageResolver initialized to {}", className);
    } catch (Throwable e) {
        String msg = String.format("MessageResolver implementation [%s] couldn't be instantiated.", className);
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to initialize the BackendPathBuilder
    className = PropertiesLoader.getUserPathBuilderImpl();
    if (StringUtils.isNullOrEmpty(className))
        throw new RuntimeException(
                "Empty BackendPathBuilder implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        userPathBuilder = (BackendPathBuilder) clazz.newInstance();
        logger.info("BackendPathBuilder initialized to {}", className);
    } catch (Throwable e) {
        String msg = "BackendPathBuilder couldn't be initialized.";
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to initialize the FilemanagerConfigBuilder
    className = PropertiesLoader.getFilemanagerConfigImpl();
    if (StringUtils.isNullOrEmpty(className))
        throw new RuntimeException(
                "Empty FilemanagerConfigBuilder implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        configBuilder = (FilemanagerConfigBuilder) clazz.newInstance();
        logger.info("FilemanagerConfigBuilder initialized to {}", className);
    } catch (Throwable e) {
        String msg = "FilemanagerConfigBuilder couldn't be initialized.";
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to instantiate the IconResolver object
    className = PropertiesLoader.getIconResolverImpl();
    if (StringUtils.isNullOrEmptyOrBlank(className))
        throw new RuntimeException(
                "Empty IconResolver implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        iconResolver = (IconResolver) clazz.newInstance();
        iconResolver.initContext(servletContext);
        logger.info("IconResolver initialized to {}", className);
    } catch (Throwable e) {
        String msg = String.format("IconResolver implementation [%s] couldn't be instantiated.", className);
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to instantiate the DimensionProvider object
    className = PropertiesLoader.getDimensionProviderImpl();
    if (StringUtils.isNullOrEmptyOrBlank(className))
        throw new RuntimeException(
                "Empty DimensionProvider implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        imageDimensionProvider = (IDimensionProvider) clazz.newInstance();
        logger.info("DimensionProvider initialized to {}", className);
    } catch (Throwable e) {
        String msg = String.format("DimensionProvider implementation [%s] couldn't be instantiated.",
                className);
        logger.error(msg);
        throw new RuntimeException(msg, e);
    }

    // try to instantiate the ExifRemover object
    className = PropertiesLoader.getExifRemoverImpl();
    if (StringUtils.isNullOrEmptyOrBlank(className)) {
        logger.warn("Empty ExifRemover implementation class name! EXIF data won't be removed.");
        exifRemover = null;
    } else {
        try {
            Class<?> clazz = Class.forName(className);
            exifRemover = (ExifRemover) clazz.newInstance();
            logger.info("ExifRemover initialized to {}", className);
        } catch (Throwable e) {
            String msg = String.format("ExifRemover implementation [%s] couldn't be instantiated.", className);
            logger.error(msg);
            throw new RuntimeException(msg, e);
        }
    }

    // try to read the dimension for thumbnails
    Matcher dimMatcher = dimensionPattern.matcher(PropertiesLoader.getThumbnailDimension());
    if (dimMatcher.matches()) {
        thumbnailDimension = new Dimension(Integer.valueOf(dimMatcher.group(1)),
                Integer.valueOf(dimMatcher.group(2)));
    }

    // try to read the dimension for preview
    dimMatcher = dimensionPattern.matcher(PropertiesLoader.getPreviewDimension());
    if (dimMatcher.matches()) {
        previewDimension = new Dimension(Integer.valueOf(dimMatcher.group(1)),
                Integer.valueOf(dimMatcher.group(2)));
    }

    // fetch the temporary directory
    File tempDir = (File) UserObjectProxy.servletContext.getAttribute(ServletContext.TEMPDIR);
    if (tempDir == null) {
        String msg = "No temporary directory according to the Servlet spec SRV.3.7.1 found!";
        logger.error(msg);
        throw new RuntimeException(msg);
    }
    tempDirectory = tempDir.toPath();

    // try to instantiate the DefaultConfigResolver object and fetches the default configuration
    className = PropertiesLoader.getDefaultConfigResolverImpl();
    if (StringUtils.isNullOrEmptyOrBlank(className))
        throw new RuntimeException(
                "Empty DefaultConfigResolver implementation class name! Depending property must be set!");
    try {
        Class<?> clazz = Class.forName(className);
        DefaultConfigResolver configResolver = (DefaultConfigResolver) clazz.newInstance();
        configResolver.initContext(servletContext);
        filemanagerDefaultConfig = configResolver.read();
        logger.info("Default configuration of the filemanager successful fetched from {}", className);
    } catch (Throwable e) {
        String msg = String.format("DefaultConfigResolver implementation [%s] couldn't be instantiated.",
                className);
        logger.error(msg);
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        throw new RuntimeException(msg, e);
    }

    // build regex pattern
    String folderExcludePatternStr = PropertiesLoader.getRegexToExcludeFolders();
    if (StringUtils.isNullOrEmptyOrBlank(folderExcludePatternStr)) {
        logger.warn("Property 'connector.regex.exclude.folders' isn't set.");
        excludeFoldersPattern = null;
    } else {
        try {
            excludeFoldersPattern = Pattern.compile(folderExcludePatternStr);
        } catch (PatternSyntaxException e) {
            throw new RuntimeException("Exclude pattern for folders couldn't be compiled!");
        }
    }

    String fileExcludePatternStr = PropertiesLoader.getRegexToExcludeFiles();
    if (StringUtils.isNullOrEmptyOrBlank(fileExcludePatternStr)) {
        logger.warn("Property 'connector.regex.exclude.files' isn't set.");
        excludeFilesPattern = null;
    } else {
        try {
            excludeFilesPattern = Pattern.compile(fileExcludePatternStr);
        } catch (PatternSyntaxException e) {
            throw new RuntimeException("Exclude pattern for files couldn't be compiled!");
        }
    }
}

From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java

/**
 * Handle a partial PUT. New content specified in request is appended to existing content in
 * oldRevisionContent (if present). This code does not support simultaneous partial updates to the
 * same resource.//from  w ww . j a  va  2s. c  o  m
 */
protected File executePartialPut(HttpServletRequest req, Range range, String sessionId) throws IOException {

    // TODO: Change this implementation to avoid Files. Try to
    // make the work on the repository implementation.

    // Append data specified in ranges to existing content for this
    // resource - create a temp. file on the local filesystem to
    // perform this operation
    // Assume just one range is specified for now

    File tempDir = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);

    // Convert all '/' characters to '.' in resourcePath
    String convertedResourcePath = sessionId.replace('/', '.');

    File contentFile = new File(tempDir, convertedResourcePath);

    if (contentFile.createNewFile()) {
        // Clean up contentFile when Tomcat is terminated
        contentFile.deleteOnExit();
    }

    try (RandomAccessFile randAccessContentFile = new RandomAccessFile(contentFile, "rw")) {

        RepositoryHttpEndpointImpl repoItemHttpElem = repoHttpManager.getHttpRepoItemElem(sessionId);

        // Copy data in oldRevisionContent to contentFile
        if (repoItemHttpElem != null) {

            try (BufferedInputStream bufOldRevStream = new BufferedInputStream(
                    repoItemHttpElem.createRepoItemInputStream(), FILE_BUFFER_SIZE)) {

                int numBytesRead;
                byte[] copyBuffer = new byte[FILE_BUFFER_SIZE];
                while ((numBytesRead = bufOldRevStream.read(copyBuffer)) != -1) {
                    randAccessContentFile.write(copyBuffer, 0, numBytesRead);
                }
            }
        }

        randAccessContentFile.setLength(range.length);

        // Append data in request input stream to contentFile
        randAccessContentFile.seek(range.start);

        int numBytesRead;

        byte[] transferBuffer = new byte[FILE_BUFFER_SIZE];

        try (BufferedInputStream requestBufInStream = new BufferedInputStream(req.getInputStream(),
                FILE_BUFFER_SIZE)) {

            while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) {
                randAccessContentFile.write(transferBuffer, 0, numBytesRead);
            }
        }
    }

    return contentFile;
}

From source file:org.eclipse.equinox.http.servlet.internal.multipart.MultipartSupportImpl.java

public MultipartSupportImpl(ExtendedServletDTO servletDTO, ServletContext servletContext) {
    this.servletDTO = servletDTO;

    // Must return non-null File. See Servlet 3.1 4.8.1
    File baseStorage = (File) servletContext.getAttribute(ServletContext.TEMPDIR);

    if (servletDTO.multipartLocation.length() > 0) {
        File storage = new File(servletDTO.multipartLocation);

        if (!storage.isAbsolute()) {
            storage = new File(baseStorage, storage.getPath());
        }// w ww .  j a  v  a 2 s.c  o m

        baseStorage = storage;
    }

    checkPermission(baseStorage, servletContext);

    baseStorage.mkdirs();

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setRepository(baseStorage);

    if (servletDTO.multipartFileSizeThreshold > 0) {
        factory.setSizeThreshold(servletDTO.multipartFileSizeThreshold);
    }

    upload = new ServletFileUpload(factory);

    if (servletDTO.multipartMaxFileSize > -1L) {
        upload.setFileSizeMax(servletDTO.multipartMaxFileSize);
    }

    if (servletDTO.multipartMaxRequestSize > -1L) {
        upload.setSizeMax(servletDTO.multipartMaxRequestSize);
    }
}