Example usage for org.springframework.web.context ContextLoader getCurrentWebApplicationContext

List of usage examples for org.springframework.web.context ContextLoader getCurrentWebApplicationContext

Introduction

In this page you can find the example usage for org.springframework.web.context ContextLoader getCurrentWebApplicationContext.

Prototype

@Nullable
public static WebApplicationContext getCurrentWebApplicationContext() 

Source Link

Document

Obtain the Spring root web application context for the current thread (i.e.

Usage

From source file:org.jboss.arquillian.spring.integration.inject.container.WebApplicationContextProducer.java

/**
 * <p>Retrieves the web application context for the given test.</p>
 *
 * @param testClass the test class//from   ww  w  .  ja  va  2 s .  co m
 *
 * @return {@link ApplicationContext} retrieves from web application
 */
private ApplicationContext getWebApplicationContext(TestClass testClass) {

    SpringWebConfiguration springWebConfiguration;
    WebApplicationContext rootContext;
    ApplicationContext applicationContext;

    rootContext = ContextLoader.getCurrentWebApplicationContext();

    if (rootContext == null) {

        throw new RuntimeException("The Spring Root Web Application Context could not be found.");
    }

    springWebConfiguration = testClass.getAnnotation(SpringWebConfiguration.class);

    if (!isEmpty(springWebConfiguration.servletName())) {

        applicationContext = getServletApplicationContext(rootContext, springWebConfiguration.servletName());

        if (applicationContext == null) {

            throw new RuntimeException("Could not find the application context for servlet: "
                    + springWebConfiguration.servletName());
        }
    } else {
        // uses the root context as the main application context
        applicationContext = rootContext;
    }

    return applicationContext;
}

From source file:com.dynamobi.ws.util.LucidDBEncoder.java

public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
    String pass1 = "" + encPass;
    String pass2 = encodePassword(rawPass, salt);

    //         System.out.println("ZZZZ rawPass= [" + rawPass + "] pass1 = [" +
    //         pass1
    //         + "] pass2 = [" + pass2 + "]");

    // We were successful, update session bean.
    if (pass1.equals(pass2)) {
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();

        UserCredentialsDataSourceAdapter ds = (UserCredentialsDataSourceAdapter) wac.getBean("myDataSource");
        ds.setPassword(rawPass);/*  w w w  .ja  v a 2 s . c  om*/
    }

    return pass1.equals(pass2);
}

From source file:de.javadesign.cdi.extension.spring.SpringBeanIntegrationExtension.java

/**
 * Listener method observes the AfterBeanDiscovery-Event.
 * /*ww w  .  ja va 2 s  .co m*/
 * @param event
 *            the AfterBeanDiscovery Event
 * @param beanManager
 *            the BeanManager
 */
public void connectCdiAndSpring(@Observes final AfterBeanDiscovery event, final BeanManager beanManager) {

    AbstractApplicationContext applicationContext = (AbstractApplicationContext) ContextLoader
            .getCurrentWebApplicationContext();

    if (applicationContext == null) {
        LOGGER.warn("No Web Spring-ApplicationContext found, try to resolve via application context provider.");
        applicationContext = (AbstractApplicationContext) ApplicationContextProvider.getApplicationContext();
    }

    if (applicationContext != null) {
        LOGGER.info("ApplicationContext found.");
        registerBeans(applicationContext, event, beanManager);
    } else {
        LOGGER.warn("No Spring-ApplicationContext found.");
    }
}

From source file:org.openspaces.pu.container.jee.jetty.JettyProcessingUnitContainer.java

public JettyProcessingUnitContainer(ApplicationContext applicationContext, WebAppContext webAppContext,
        ContextHandlerCollection contextHandlerCollection, JettyHolder jettyHolder,
        List<FreePortGenerator.PortHandle> portHandels) {
    this.applicationContext = applicationContext;
    this.webAppContext = webAppContext;
    this.contextHandlerCollection = contextHandlerCollection;
    this.jettyHolder = jettyHolder;
    this.webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
    if (webApplicationContext == null) {
        webApplicationContext = applicationContext;
    }/* w w  w  .ja  v a 2s.c o  m*/
    this.portHandels = portHandels;
}

From source file:com.envision.envservice.filter.RedmineFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Content-Type", "application/json; charset=utf-8");
    String requestType = request.getMethod();
    String url = "";
    String api_key = "";
    String param = "";
    String result = "";
    if (requestType == "GET" || "GET".equals(requestType)) {
        url = getRedmineUrl(request.getRequestURL().toString());
        api_key = getSessionApiKey(request);
        if (api_key == null || "".equals(api_key)) {
            return;
        }/*  w  w w .j av  a  2s . c o  m*/
        WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext();
        RedmineHttpRequestService redmineHttpRequestService = (RedmineHttpRequestService) webAppContext
                .getBean("redmineHttpRequestService");
        result = redmineHttpRequestService.doGET(url, api_key);
    } else if (requestType == "POST" || "POST".equals(requestType)) {
        url = getRedmineUrl(request.getRequestURL().toString());
        api_key = getSessionApiKey(request);
        if (api_key == null || "".equals(api_key)) {
            return;
        }
        param = getParam(request.getInputStream());
        WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext();
        RedmineHttpRequestService redmineHttpRequestService = (RedmineHttpRequestService) webAppContext
                .getBean("redmineHttpRequestService");
        result = redmineHttpRequestService.doPost(url, param, api_key);
    } else if (requestType == "PUT" || "PUT".equals(requestType)) {
        url = getRedmineUrl(request.getRequestURL().toString());
        api_key = getSessionApiKey(request);
        if (api_key == null || "".equals(api_key)) {
            return;
        }
        param = getParam(request.getInputStream());
        WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext();
        RedmineHttpRequestService redmineHttpRequestService = (RedmineHttpRequestService) webAppContext
                .getBean("redmineHttpRequestService");
        result = redmineHttpRequestService.doPut(url, param, api_key);
    } else {
        return;
    }

    response.getWriter().write(result);
    return;

}

From source file:org.carewebframework.ui.spring.AppContextFinder.java

/**
 * Returns the root application context.
 * /*w w w.j av a  2s.c  o  m*/
 * @see org.carewebframework.api.spring.IAppContextFinder#getRootAppContext()
 * @return The root application context.
 */
@Override
public ApplicationContext getRootAppContext() {
    return rootContext != null ? rootContext : ContextLoader.getCurrentWebApplicationContext();
}

From source file:de.acosix.alfresco.mtsupport.repo.integration.AuthenticationTest.java

@Test
public void loginNonExistingUserPMaierDefaultTenant() {
    final WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
    final AuthenticationService authenticationService = context.getBean("AuthenticationService",
            AuthenticationService.class);

    this.thrown.expect(AuthenticationException.class);
    this.thrown.expectMessage("Failed to authenticate");
    authenticationService.authenticate("pmaier", "pmaier".toCharArray());
}

From source file:com.taobao.ad.easyschedule.server.JobHttpServer.java

@Override
public void run() {
    try {/*from  w ww.j a v  a  2s.  c om*/
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(Integer.parseInt(Const.SERVER_PORT)),
                0);
        httpServer.createContext(Const.SERVER_CONTEXT, new HttpHandler() {
            @Override
            public void handle(final HttpExchange exchange) throws IOException {
                JobResult result = JobResult.succcessResult();
                String queryPath = exchange.getRequestURI().getPath();
                String queryStr = exchange.getRequestURI().getQuery();
                if (StringUtils.isEmpty(queryStr) || StringUtils.isEmpty(queryPath)) {
                    result = JobResult.errorResult(JobResult.RESULTCODE_PARAMETER_ILLEGAL,
                            "??");
                } else {
                    try {
                        queryPath = queryPath.replaceAll(Const.SERVER_CONTEXT, "");
                        JobData jobData = HttpJobUtils.createJobData(queryStr);
                        String beanId = jobData.getData().get(JobData.JOBDATA_DATA_BEANID);
                        if (StringUtils.isEmpty(beanId)) {
                            result = JobResult.errorResult(JobResult.RESULTCODE_PARAMETER_ILLEGAL,
                                    "???");
                        } else {
                            if (Const.DEPLOY_MODE.equals("dev")) {
                                Long signTime = System.currentTimeMillis() / 1000;
                                String token = TokenUtils.generateToken(signTime.toString());
                                jobData.setSignTime(signTime.toString());
                                jobData.setToken(token);
                            }
                            result = HttpJobUtils.checkJobData(jobData);
                            if (result.isSuccess()) {
                                if (queryPath.equals(Const.QUERYPATH_DOSTDJOB)) {
                                    WebApplicationContext context = ContextLoader
                                            .getCurrentWebApplicationContext();
                                    JobExecutor executor = (JobExecutor) context.getBean(beanId);
                                    result = HttpJobExecutor.getInstance().execute(jobData, executor);
                                } else {
                                    result = JobResult.errorResult(JobResult.RESULTCODE_PARAMETER_ILLEGAL,
                                            "" + queryPath);
                                }
                            }
                        }
                    } catch (Exception e) {
                        result = JobResult.errorResult(JobResult.RESULTCODE_OTHER_ERR, "");
                        logger.info("|" + queryStr);
                    }
                }
                JSONObject json = (JSONObject) JSONObject.toJSON(result);
                exchange.getResponseHeaders().set("Content-type", "application/json;charset=utf-8");
                exchange.sendResponseHeaders(200, 0L);
                OutputStream os = exchange.getResponseBody();
                os.write(json.toString().getBytes("utf-8"));
                os.close();
            }
        });
        httpServer.start();
    } catch (Throwable e) {
        logger.error("JobHttpServer.run is fail:" + e.getMessage(), e);
    }
}

From source file:com.sp2p.task.JobInTimeTask.java

private Object getBean(String beanName) {
    return ContextLoader.getCurrentWebApplicationContext().getBean(beanName);
}

From source file:de.acosix.alfresco.mtsupport.repo.integration.AuthenticationTest.java

@Test
public void loginExistingUserAFaustDefaultTenant() {
    final WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
    final AuthenticationService authenticationService = context.getBean("AuthenticationService",
            AuthenticationService.class);

    authenticationService.authenticate("afaust", "afaust".toCharArray());
}