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.fao.fenix.web.modules.core.server.upload.CodeListUploaderServlet.java

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

    // useful stuff
    UploadListener listener = new UploadListener(request, 30);
    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    ServletFileUpload upload = new ServletFileUpload(factory);
    ServletContext servletContext = this.getServletConfig().getServletContext();
    Long codeListID = null;/*from   w w w.  ja v a 2s  . c  o m*/

    // spring beans
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    DcmtImporter dcmtImporter = (DcmtImporter) wac.getBean("dcmtImporter");

    try {

        List<FileItem> fileItemList = (List<FileItem>) upload.parseRequest(request);

        // coding system
        FileItem codingSystemItem = findFileItemByCode("CODING_SYSTEM", fileItemList);

        // upload policy
        FileItem policyItem = findFileItemByCode("POLICY", fileItemList);
        String policyValue = extractValue(policyItem);
        UploadPolicy policy = UploadPolicy.valueOfIgnoreCase(policyValue);

        // delimiter
        FileItem delimiterItem = findFileItemByCode("DELIMITER", fileItemList);
        String delimiterValue = extractValue(delimiterItem);

        // coding system name
        FileItem codingSystemNameItem = findFileItemByCode("CODING_SYSTEM_NAME", fileItemList);
        String codingSystemNameValue = extractValue(codingSystemNameItem);

        // coding system type
        FileItem codingSystemTypeItem = findFileItemByCode("CODING_SYSTEM_TYPE", fileItemList);
        String codingSystemTypeValue = extractValue(codingSystemTypeItem);
        CodingType codingType = CodingType.valueOfIgnoreCase(codingSystemTypeValue);

        // abstract
        FileItem abstractItem = findFileItemByCode("ABSTRACT", fileItemList);
        String abstractabstract = extractValue(abstractItem);

        // source
        Source source = createSource(fileItemList);

        File file = createMetadata(codingSystemNameValue, codingType, abstractabstract, source);
        InputStream metadataStream = new FileInputStream(file);

        codeListID = dcmtImporter.importCodesFromCSV(metadataStream, codingSystemItem.getInputStream(),
                delimiterValue, policy);
        LOGGER.info("CodeList imported/updated with ID: " + codeListID);

    } catch (FileUploadException e) {
        LOGGER.error(e.getMessage());
        throw new FenixException(e.getMessage());
    }

    // done!
    response.getOutputStream().print("codeListID:" + codeListID);
}

From source file:org.fireflow.console.servlet.repository.UploadDefinitionsServlet.java

public void init() throws ServletException {
    //??spring bean
    springCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    fireContext = (RuntimeContext) springCtx.getBean(RuntimeContext.Fireflow_Runtime_Context_Name);
    transactionTemplate = (TransactionTemplate) springCtx.getBean("demoTransactionTemplate");

}

From source file:org.grails.web.errors.GrailsWrappedRuntimeException.java

/**
 * @param servletContext The ServletContext instance
 * @param t The exception that was thrown
 *//*from ww  w .j a  v  a 2  s . c om*/
public GrailsWrappedRuntimeException(ServletContext servletContext, Throwable t) {
    super(t.getMessage(), t);
    this.cause = t;
    Throwable cause = t;

    FastStringPrintWriter pw = FastStringPrintWriter.newInstance();
    cause.printStackTrace(pw);
    stackTrace = pw.toString();

    while (cause.getCause() != cause) {
        if (cause.getCause() == null) {
            break;
        }
        cause = cause.getCause();
    }

    stackTraceLines = stackTrace.split("\\n");

    if (cause instanceof MultipleCompilationErrorsException) {
        MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) cause;
        Object message = mcee.getErrorCollector().getErrors().iterator().next();
        if (message instanceof SyntaxErrorMessage) {
            SyntaxErrorMessage sem = (SyntaxErrorMessage) message;
            lineNumber = sem.getCause().getLine();
            className = sem.getCause().getSourceLocator();
            sem.write(pw);
        }
    } else {
        Matcher m1 = PARSE_DETAILS_STEP1.matcher(stackTrace);
        Matcher m2 = PARSE_DETAILS_STEP2.matcher(stackTrace);
        Matcher gsp = PARSE_GSP_DETAILS_STEP1.matcher(stackTrace);
        try {
            if (gsp.find()) {
                className = gsp.group(2);
                lineNumber = Integer.parseInt(gsp.group(3));
                gspFile = URL_PREFIX + "views/" + gsp.group(1) + '/' + className;
            } else {
                if (m1.find()) {
                    do {
                        className = m1.group(1);
                        lineNumber = Integer.parseInt(m1.group(2));
                    } while (m1.find());
                } else {
                    while (m2.find()) {
                        className = m2.group(1);
                        lineNumber = Integer.parseInt(m2.group(2));
                    }
                }
            }
        } catch (NumberFormatException nfex) {
            // ignore
        }
    }

    LineNumberReader reader = null;
    try {
        checkIfSourceCodeAware(t);
        checkIfSourceCodeAware(cause);

        if (getLineNumber() > -1) {
            String fileLocation;
            String url = null;

            if (fileName != null) {
                fileLocation = fileName;
            } else {
                String urlPrefix = "";
                if (gspFile == null) {
                    fileName = className.replace('.', '/') + ".groovy";

                    GrailsApplication application = WebApplicationContextUtils
                            .getRequiredWebApplicationContext(servletContext)
                            .getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class);
                    // @todo Refactor this to get the urlPrefix from the ArtefactHandler
                    if (application.isArtefactOfType(ControllerArtefactHandler.TYPE, className)) {
                        urlPrefix += "/controllers/";
                    } else if (application.isArtefactOfType(TagLibArtefactHandler.TYPE, className)) {
                        urlPrefix += "/taglib/";
                    } else if (application.isArtefactOfType(ServiceArtefactHandler.TYPE, className)) {
                        urlPrefix += "/services/";
                    }
                    url = URL_PREFIX + urlPrefix + fileName;
                } else {
                    url = gspFile;
                    GrailsApplicationAttributes attrs = null;
                    try {
                        attrs = grailsApplicationAttributesConstructor.newInstance(servletContext);
                    } catch (Exception e) {
                        ReflectionUtils.rethrowRuntimeException(e);
                    }
                    ResourceAwareTemplateEngine engine = attrs.getPagesTemplateEngine();
                    lineNumber = engine.mapStackLineNumber(url, lineNumber);
                }
                fileLocation = "grails-app" + urlPrefix + fileName;
            }

            InputStream in = null;
            if (!GrailsStringUtils.isBlank(url)) {
                in = servletContext.getResourceAsStream(url);
                LOG.debug("Attempting to display code snippet found in url " + url);
            }
            if (in == null) {
                Resource r = null;
                try {
                    r = resolver.getResource(fileLocation);
                    in = r.getInputStream();
                } catch (Throwable e) {
                    r = resolver.getResource("file:" + fileLocation);
                    if (r.exists()) {
                        try {
                            in = r.getInputStream();
                        } catch (IOException e1) {
                            // ignore
                        }
                    }
                }
            }

            if (in != null) {
                reader = new LineNumberReader(new InputStreamReader(in, "UTF-8"));
                String currentLine = reader.readLine();
                StringBuilder buf = new StringBuilder();
                while (currentLine != null) {
                    int currentLineNumber = reader.getLineNumber();
                    if ((lineNumber > 0 && currentLineNumber == lineNumber - 1)
                            || (currentLineNumber == lineNumber)) {
                        buf.append(currentLineNumber).append(": ").append(currentLine).append("\n");
                    } else if (currentLineNumber == lineNumber + 1) {
                        buf.append(currentLineNumber).append(": ").append(currentLine);
                        break;
                    }
                    currentLine = reader.readLine();
                }
                codeSnippet = buf.toString().split("\n");
            }
        }
    } catch (IOException e) {
        LOG.warn("[GrailsWrappedRuntimeException] I/O error reading line diagnostics: " + e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.granite.grails.web.GrailsWebSWFServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    servletContextLoader = new ServletContextResourceLoader(servletConfig.getServletContext());
    ApplicationContext springContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletConfig.getServletContext());
    if (springContext.containsBean(GroovyPageResourceLoader.BEAN_ID)) {
        resourceLoader = (ResourceLoader) springContext.getBean(GroovyPageResourceLoader.BEAN_ID);
    }/*from  ww w.  j a  v  a  2 s.  com*/

    grailsAttributes = new DefaultGrailsApplicationAttributes(servletConfig.getServletContext());
}

From source file:org.hdiv.listener.InitListener.java

/**
 * Initialize ServletContext scoped objects.
 * //from  w ww. j  ava 2  s  .  com
 * @param servletContext
 *            ServletContext instance
 */
protected void initServletContext(ServletContext servletContext) {

    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    this.config = (HDIVConfig) wac.getBean("config");
    this.dataComposerFactory = (DataComposerFactory) wac.getBean("dataComposerFactory");
    this.stateUtil = (StateUtil) wac.getBean("stateUtil");
    this.session = (ISession) wac.getBean("sessionHDIV");

    // Init servlet context scoped objects
    HDIVUtil.setHDIVConfig(this.config, servletContext);

    IApplication application = (IApplication) wac.getBean("application");
    HDIVUtil.setApplication(application, servletContext);

    ISession session = (ISession) wac.getBean("sessionHDIV");
    HDIVUtil.setISession(session, servletContext);

    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBeanClassLoader(wac.getClassLoader());
    String messageSourcePath = (String) wac.getBean("messageSourcePath");
    messageSource.setBasename(messageSourcePath);
    HDIVUtil.setMessageSource(messageSource, servletContext);

    LinkUrlProcessor linkUrlProcessor = (LinkUrlProcessor) wac.getBean("linkUrlProcessor");
    HDIVUtil.setLinkUrlProcessor(linkUrlProcessor, servletContext);

    FormUrlProcessor formUrlProcessor = (FormUrlProcessor) wac.getBean("formUrlProcessor");
    HDIVUtil.setFormUrlProcessor(formUrlProcessor, servletContext);

    this.servletContextInitialized = true;
}

From source file:org.hoteia.qalingo.core.web.servlet.DispatcherServlet.java

private void initPlatformTheme(HttpServletRequest request) {
    final ServletContext context = getServletContext();
    final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    final RequestUtil requestUtil = (RequestUtil) ctx.getBean("requestUtil");

    // THEME/*w w  w  .ja va2s.c  o  m*/
    try {
        final RequestData requestData = requestUtil.getRequestData(request);
        final MarketArea marketArea = requestData.getMarketArea();
        if (marketArea != null && StringUtils.isNotEmpty(marketArea.getTheme())) {
            String themeFolder = marketArea.getTheme();
            requestUtil.updateCurrentTheme(request, themeFolder);
        } else {
            final Market market = requestData.getMarket();
            if (market != null && StringUtils.isNotEmpty(market.getTheme())) {
                String themeFolder = market.getTheme();
                requestUtil.updateCurrentTheme(request, themeFolder);
            } else {
                final MarketPlace marketPlace = requestData.getMarketPlace();
                if (marketPlace != null && StringUtils.isNotEmpty(marketPlace.getTheme())) {
                    String themeFolder = marketPlace.getTheme();
                    requestUtil.updateCurrentTheme(request, themeFolder);
                }
            }
        }

    } catch (Exception e) {
        logger.error("", e);
    }
}

From source file:org.hoteia.qalingo.core.web.servlet.DispatcherServlet.java

private void initPlatformDevice(HttpServletRequest request) {
    final ServletContext context = getServletContext();
    final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    final RequestUtil requestUtil = (RequestUtil) ctx.getBean("requestUtil");

    // DEVICE//w  w  w.  j  a v  a2 s . c o m
    try {
        final RequestData requestData = requestUtil.getRequestData(request);

        final WURFLHolder wurfl = (WURFLHolder) ctx.getBean("wurflHolder");
        final WURFLManager manager = wurfl.getWURFLManager();
        Device device = manager.getDeviceForRequest(request);
        String deviceFolder = "default";
        if (device != null) {
            boolean isSmartPhone = BooleanUtils.toBoolean(device.getVirtualCapability("is_smartphone"));
            boolean isIPhoneOs = BooleanUtils.toBoolean(device.getVirtualCapability("is_iphone_os"));
            boolean isAndroid = BooleanUtils.toBoolean(device.getVirtualCapability("is_android"));
            if (isSmartPhone || isIPhoneOs || isAndroid) {
                deviceFolder = "mobile";
            }
        }
        requestUtil.updateCurrentDevice(requestData, deviceFolder);

    } catch (Exception e) {
        logger.error("", e);
    }
}

From source file:org.jahia.ajax.gwt.content.server.GWTFileManagerUploadServlet.java

@SuppressWarnings("unchecked")
private SessionNamedDataStorage<UploadedPendingFile> getFileStorage() {
    if (fileStorage != null) {
        return fileStorage;
    }/*from   w  w w. ja  v a 2  s.c o  m*/
    synchronized (this) {
        if (fileStorage != null) {
            return fileStorage;
        }
        ApplicationContext context = WebApplicationContextUtils
                .getRequiredWebApplicationContext(getServletContext());
        fileStorage = (SessionNamedDataStorage<UploadedPendingFile>) context
                .getBean("UploadedPendingFileStorage");
        return fileStorage;
    }
}

From source file:org.jlibrary.web.servlet.JLibraryContentLoaderServlet.java

@Override
public void init() throws ServletException {

    super.init();

    try {//from   ww  w .  j a  va2  s. c o  m
        ApplicationContext context = WebApplicationContextUtils
                .getRequiredWebApplicationContext(getServletContext());
        ConfigurationService configService = (ConfigurationService) context.getBean("template");
        TicketService.getTicketService().init(configService);

        repositoryService = JLibraryServiceFactory.getInstance(profile).getRepositoryService();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.jlibrary.web.servlet.JLibraryServlet.java

@Override
public void init() throws ServletException {

    context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    super.init();
}