Example usage for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext

List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext

Introduction

In this page you can find the example usage for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext.

Prototype

public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc)
        throws IllegalStateException 

Source Link

Document

Find the root WebApplicationContext for this web app, typically loaded via org.springframework.web.context.ContextLoaderListener .

Usage

From source file:org.codehaus.groovy.grails.web.util.WebUtils.java

/**
 * Looks up all of the HandlerInterceptor instances registered for the application
 *
 * @param servletContext The ServletContext instance
 * @return An array of HandlerInterceptor instances
 *///from   www  .  j av  a  2 s. c om
public static HandlerInterceptor[] lookupHandlerInterceptors(ServletContext servletContext) {
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    final Collection<HandlerInterceptor> allHandlerInterceptors = new ArrayList<HandlerInterceptor>();

    WebRequestInterceptor[] webRequestInterceptors = lookupWebRequestInterceptors(servletContext);
    for (WebRequestInterceptor webRequestInterceptor : webRequestInterceptors) {
        allHandlerInterceptors.add(new WebRequestHandlerInterceptorAdapter(webRequestInterceptor));
    }
    final Collection<HandlerInterceptor> handlerInterceptors = wac.getBeansOfType(HandlerInterceptor.class)
            .values();

    allHandlerInterceptors.addAll(handlerInterceptors);
    return allHandlerInterceptors.toArray(new HandlerInterceptor[allHandlerInterceptors.size()]);
}

From source file:org.codehaus.groovy.grails.web.util.WebUtils.java

/**
 * Looks up all of the WebRequestInterceptor instances registered with the application
 *
 * @param servletContext The ServletContext instance
 * @return An array of WebRequestInterceptor instances
 *///www  .  j a  v  a  2s  .co m
public static WebRequestInterceptor[] lookupWebRequestInterceptors(ServletContext servletContext) {
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    final Collection<WebRequestInterceptor> webRequestInterceptors = wac
            .getBeansOfType(WebRequestInterceptor.class).values();
    return webRequestInterceptors.toArray(new WebRequestInterceptor[webRequestInterceptors.size()]);
}

From source file:org.codehaus.groovy.grails.web.util.WebUtils.java

/**
 * Looks up the UrlMappingsHolder instance
 *
 * @return The UrlMappingsHolder/*from   ww w  .  ja  va2  s . c  o  m*/
 * @param servletContext The ServletContext object
 */
public static UrlMappingsHolder lookupUrlMappings(ServletContext servletContext) {
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    return (UrlMappingsHolder) wac.getBean(UrlMappingsHolder.BEAN_ID);
}

From source file:org.codehaus.groovy.grails.web.util.WebUtils.java

/**
 * Looks up the GrailsApplication instance
 *
 * @return The GrailsApplication instance
 *//*from  w w w  . ja  v  a2s . c  om*/
public static GrailsApplication lookupApplication(ServletContext servletContext) {
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    return (GrailsApplication) wac.getBean(GrailsApplication.APPLICATION_ID);
}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    // get init param
    servletConfig = config;//from   w  w w  . j av  a 2  s  .  com
    parameterName = config.getInitParameter("parameterName");
    forwardPathUpload = config.getInitParameter("forwardPathUpload");
    forwardPathDownload = config.getInitParameter("forwardPathDownload");
    forwardPathList = config.getInitParameter("forwardPathList");
    forwardPathRead = config.getInitParameter("forwardPathRead");
    forwardPathDelete = config.getInitParameter("forwardPathDelete");

    // set service
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(config.getServletContext());

    PropertiesService propertiesService = (PropertiesService) ctx.getBean("propertiesService");

    // overwrite configuration
    characterEncoding = propertiesService.getString("file.default.character.encoding", characterEncoding);
    sizeThreshold = propertiesService.getInt("file.default.file.size.threshold", sizeThreshold);
    fileSizeMax = propertiesService.getLong("file.default.file.size.max", fileSizeMax);
    requestSizeMax = propertiesService.getLong("file.default.request.size.max", requestSizeMax);
    realRepositoryPath = propertiesService.getString("file.default.real.repository.path", realRepositoryPath);
    tempRepositoryPath = propertiesService.getString("file.default.temp.repository.path", tempRepositoryPath);
    repositoryType = RepositoryType.valueOf(
            propertiesService.getString("file.default.real.repository.type", repositoryType.toString()));
    // mkdirs
    File file = new File(realRepositoryPath);
    if (!file.exists()) {
        try {
            FileUtils.forceMkdir(file);
        } catch (IOException e) {
            StringBuilder sb = new StringBuilder();
            sb.append("Cannot make directory: ");
            sb.append(file.toString());
            logger.error(sb.toString());
            throw new ServletException(sb.toString());
        }
    }
    file = new File(tempRepositoryPath);
    if (!file.exists()) {
        try {
            FileUtils.forceMkdir(file);
        } catch (IOException e) {
            StringBuilder sb = new StringBuilder();
            sb.append("Cannot make directory: ");
            sb.append(file.toString());
            logger.error(sb.toString());
            throw new ServletException(sb.toString());
        }
    }

}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ??  .</br> ? ? ?? ?  , (: ?) ? mapId  . ?
 *  ?? ? repositoryType ,  ?//from w  ww .  j a  v  a  2 s.c  o  m
 * org.codelabor.system.file.RepositoryType .
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
@SuppressWarnings("unchecked")
protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String mapId = (String) paramMap.get("mapId");
    RepositoryType acceptedRepositoryType = repositoryType;
    String requestedRepositoryType = (String) paramMap.get("repositoryType");
    if (StringUtils.isNotEmpty(requestedRepositoryType)) {
        acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType);
    }

    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(sizeThreshold);
        factory.setRepository(new File(tempRepositoryPath));
        factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(this.getServletContext()));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(fileSizeMax);
        upload.setSizeMax(requestSizeMax);
        upload.setHeaderEncoding(characterEncoding);
        upload.setProgressListener(new FileUploadProgressListener());
        try {
            List<FileItem> fileItemList = upload.parseRequest(request);
            Iterator<FileItem> iter = fileItemList.iterator();

            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                logger.debug("fileItem: {}", fileItem.toString());
                FileDTO fileDTO = null;
                if (fileItem.isFormField()) {
                    paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding));
                } else {
                    if (fileItem.getName() == null || fileItem.getName().length() == 0)
                        continue;
                    // set DTO
                    fileDTO = new FileDTO();
                    fileDTO.setMapId(mapId);
                    fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName()));
                    if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) {
                        fileDTO.setUniqueFilename(getUniqueFilename());
                    }
                    fileDTO.setContentType(fileItem.getContentType());
                    fileDTO.setRepositoryPath(realRepositoryPath);
                    logger.debug("fileDTO: {}", fileDTO.toString());
                    UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO);
                }
                if (fileDTO != null)
                    fileManager.insertFile(fileDTO);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        }
    } else {
        paramMap = RequestUtils.getParameterMap(request);
    }
    try {
        processParameters(paramMap);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        throw e;
    }
    dispatch(request, response, forwardPathUpload);
}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 *  ?? .//  w w  w . j a  v  a 2s  .c o m
 * 
 * @return  ?
 * @throws Exception
 *             
 */
protected String getUniqueFilename() throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    IdGenService uniqueFilenameGenerationService = (IdGenService) ctx
            .getBean("uniqueFilenameGenerationService");
    return uniqueFilenameGenerationService.getNextStringId();
}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ? ?? .</br>? ??// w ww  .j a  va2  s.  c om
 * org.codelabor.system.file.FileConstants.FILE_LIST_KEY?  attribute?
 * ??. Map Id?  ? Map Id
 * org.codelabor.system.file.FileConstants.MAP_ID?  attribute? ??.
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
protected void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String mapId = (String) paramMap.get("mapId");
    String repositoryType = (String) paramMap.get("repositoryType");

    IdGenService mapIdGenService = (IdGenService) ctx.getBean("sequenceMapIdGenService");

    List<FileDTO> fileDTOList = null;
    try {
        if (StringUtils.isEmpty(repositoryType)) {
            if (StringUtils.isEmpty(mapId)) {
                fileDTOList = fileManager.selectFileAll();
            } else {
                fileDTOList = fileManager.selectFileByMapId(mapId);
            }
        } else {
            switch (RepositoryType.valueOf(repositoryType)) {
            case DATABASE:
                fileDTOList = fileManager.selectFileByRepositoryType(RepositoryType.DATABASE);
                break;
            case FILE_SYSTEM:
                fileDTOList = fileManager.selectFileByRepositoryType(RepositoryType.FILE_SYSTEM);
                break;
            default:
                logger.error("Invalid repository type: {}", repositoryType);
                throw new InvalidRepositoryTypeException(repositoryType);
            }
        }
        request.setAttribute(org.codelabor.system.file.FileConstants.FILE_LIST_KEY, fileDTOList);
        request.setAttribute(org.codelabor.system.file.FileConstants.MAP_ID, mapIdGenService.getNextStringId());
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    }
    dispatch(request, response, forwardPathList);
}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ?? ??./* w  w w . j  a  va  2  s  .  co m*/
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
protected void view(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String fileId = (String) paramMap.get("fileId");

    StringBuilder sb = new StringBuilder();

    FileDTO fileDTO;
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        sb.setLength(0);
        sb.append(repositoryPath);
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);

    }
    response.setContentType(fileDTO.getContentType());

    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ?? .</br> ?? ? Id ? fileId  .  
 * org.codelabor.system.daos.AFFECTED_ROW_COUNT?  attribute? ??.
 * /*www .ja va  2  s . c o  m*/
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
protected void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    int affectedRowCount = 0;

    // fileId 
    String[] fileIdList = request.getParameterValues("fileId");
    if (ArrayUtils.isEmpty(fileIdList)) {
        logger.warn("fileIdList is empty.");
    } else {
        try {
            affectedRowCount += fileManager.deleteFileByFileId(fileIdList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        }
    }

    // mapId 
    String[] mapIdList = request.getParameterValues("mapId");
    if (ArrayUtils.isEmpty(mapIdList)) {
        logger.warn("mapIdList is empty.");
    } else {
        try {
            affectedRowCount += fileManager.deleteFileByMapId(mapIdList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        }
    }
    request.setAttribute(AFFECTED_ROW_COUNT, affectedRowCount);
    dispatch(request, response, forwardPathDelete);
}