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

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

Introduction

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

Prototype

@Nullable
public static WebApplicationContext getWebApplicationContext(ServletContext sc) 

Source Link

Document

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

Usage

From source file:com.github.mjeanroy.junit.servers.samples.jetty.java.IndexWithRunnerTest.java

@Test
public void it_should_have_an_index() {
    HttpResponse rsp = client.prepareGet("/index")
            .addCookie(cookie("foo", "bar", null, null, 0, 0, false, false)).execute();

    String message = rsp.body();/*  w ww .ja v a  2 s . co m*/
    assertThat(message).isNotEmpty().isEqualTo("Hello bar");

    // Try to get servlet context
    ServletContext servletContext = server.getServletContext();
    assertThat(servletContext).isNotNull();

    // Try to retrieve spring webApplicationContext
    WebApplicationContext webApplicationContext = WebApplicationContextUtils
            .getWebApplicationContext(servletContext);
    assertThat(webApplicationContext).isNotNull();
}

From source file:com.ewcms.component.checkcode.web.ImageCaptchaServlet.java

protected CaptchaService getCaptchaService() {
    ServletContext application = getServletContext();
    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
    return (CaptchaService) wac.getBean("captchaService");
}

From source file:net.naijatek.myalumni.util.taglib.LatestMembersTag.java

/**
 * Includes the body of the tag if the page attribute equals the value set
 * in the 'match' attribute.//from   w w  w.  j  a  v a  2s .c om
 * 
 * @return SKIP_BODY if equalsAttribute body content does not equal the
 *         value of the match attribute, EVAL_BODY_include if it does
 * @throws JspException
 */
@Override
public final int doStartTag() throws JspException {
    request = (HttpServletRequest) pageContext.getRequest();

    WebApplicationContext wac = WebApplicationContextUtils
            .getWebApplicationContext(pageContext.getServletContext());
    memService = (IMemberService) wac.getBean(BaseConstants.SERVICE_MEMBER_LOOKUP);

    return EVAL_BODY_BUFFERED;
}

From source file:com.webapp.tags.MainNav.java

/**
 * Retrieve the instance of the WebApp which is configured with components, 
 * as opposed to using static members./*from   w  ww  .j  a va 2  s . co m*/
 * 
 * <p>This will have the currently set list of features and menu locations 
 * for this application instance.</p>
 * 
 * @return The currently configured system description with all the features specified.
 */
private WebApp getSystemDescription() {

    if (webapp == null) {
        WebApplicationContext applicationContext = WebApplicationContextUtils
                .getWebApplicationContext(((PageContext) getJspContext()).getServletContext());

        if (applicationContext != null) {
            String[] names = applicationContext.getBeanDefinitionNames();
            if (names.length > 0) {
                for (int x = 0; x < names.length; x++) {
                    LOG.trace("BEAN: " + names[x]);
                }
            } else {
                LOG.error("There are NO BEAN NAMES!");
            }
        } else {
            LOG.error("There is no application context available to the custom tags!");
        }

        if (applicationContext != null && applicationContext.containsBean(WebApp.SYSTEM_DESCRIPTION)) {
            webapp = (WebApp) applicationContext.getBean(WebApp.SYSTEM_DESCRIPTION);
        }
        if (webapp == null) {
            LOG.warn("Could not get system description...creating one");
            webapp = new WebApp();
        }
    }

    return webapp;
}

From source file:it.cilea.osd.common.validation.BaseValidator.java

protected String getValidationMessage(String errors) {
    String message = "";
    if (errors != null && errors.length() != 0) {
        WebContext ctx = WebContextFactory.get();
        MessageSource messageSource = WebApplicationContextUtils
                .getWebApplicationContext(ctx.getServletContext());
        //il messaggio deve essere ripescato dal resource bundle
        ResourceBundle resourceBundle = ResourceBundle.getBundle(Constants.BUNDLE_KEY,
                ctx.getHttpServletRequest().getLocale());
        message = resourceBundle.getString(errors);
    }//from  w w  w  .  j  a  va 2 s. c om
    return message;
}

From source file:org.openmeetings.servlet.outputhandler.ActivateUser.java

private Fieldmanagment getFieldmanagment() {
    try {//from  ww w .  j  a v a 2 s.co  m
        if (!ScopeApplicationAdapter.initComplete) {
            return null;
        }
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        return (Fieldmanagment) context.getBean("fieldmanagment");
    } catch (Exception err) {
        log.error("[getgetFieldmanagment()]", err);
    }
    return null;
}

From source file:com.github.mjeanroy.junit.servers.samples.jetty.java.IndexWithRulesTest.java

@Test
public void it_should_have_an_index() {
    String url = url() + "index";
    String message = restTemplate.getForObject(url, String.class);
    assertThat(message).isNotEmpty().isEqualTo("Hello World");

    // Try to get servlet context
    ServletContext servletContext = serverRule.getServer().getServletContext();
    assertThat(servletContext).isNotNull();

    // Try to retrieve spring webApplicationContext
    WebApplicationContext webApplicationContext = WebApplicationContextUtils
            .getWebApplicationContext(servletContext);
    assertThat(webApplicationContext).isNotNull();
}

From source file:edu.uoc.videochat.LTIAuthenticator.java

/**
 * @param request//from w w  w .j a  v  a  2s.  c  o  m
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response) This is a template of LTI Provider
 * @author
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String nextPage = "error";
    String params = "";
    HttpSession session = request.getSession();
    //ModelAndView model = new ModelAndView();
    session.setAttribute(Constants.USER_SESSION, null);
    session.setAttribute(Constants.COURSE_SESSION, null);
    session.setAttribute(Constants.MEETING_SESSION, null);
    session.setAttribute(Constants.USER_METTING_SESSION, null);
    session.setAttribute(Constants.USER_LANGUAGE, null);

    try {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        //ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
        UserDao userDao = (UserDao) context.getBean("UserDao");
        CourseDao courseDao = context.getBean(CourseDao.class);
        UserCourseDao userCourseDao = context.getBean(UserCourseDao.class);
        RoomDao roomDao = context.getBean(RoomDao.class);

        request.setCharacterEncoding("UTF-8");
        //1. Check if LTI call is valid
        LTIEnvironment LTIEnvironment;
        LTIEnvironment = new LTIEnvironment();
        if (LTIEnvironment.is_lti_request(request)) {

            LTIEnvironment.parseRequest(request);
            if (LTIEnvironment.isAuthenticated()) {

                //2. Get the values of user and course      
                String username = Util.sanitizeString(LTIEnvironment.getUserName());
                //TODO mirar si cal posar
                /*if (username.startsWith(LTIEnvironment.getResourcekey()+":")) {
                         username = username.substring((LTIEnvironment.getResourcekey()+":").length());
                         }*/
                String full_name = LTIEnvironment.getFullName();

                String first_name = LTIEnvironment.getParameter(Constants.FIRST_NAME_LTI_PARAMETER);
                String last_name = LTIEnvironment.getParameter(Constants.LAST_NAME_LTI_PARAMETER);

                String email = LTIEnvironment.getEmail();
                String user_image = LTIEnvironment.getUser_image();

                //3. Get the role
                boolean is_instructor = LTIEnvironment.isInstructor();
                boolean is_course_autz = LTIEnvironment.isCourseAuthorized();

                //4. Get course data
                String course_key = Util.sanitizeString(LTIEnvironment.getCourseKey());
                String course_label = LTIEnvironment.getCourseName();
                String resource_key = Util.sanitizeString(LTIEnvironment.getResourceKey());
                String resource_label = LTIEnvironment.getResourceTitle();

                //LTIEnvironment.getParameter(lis_person_name_given);
                //5. Get the locale
                String locale = LTIEnvironment.getLocale();

                java.util.Date date = new java.util.Date();

                //Steps to integrate with your applicationa
                boolean redirectToPlayer = LTIEnvironment
                        .getCustomParameter(Constants.PLAYER_CUSTOM_LTI_PARAMETER, request) != null;
                boolean is_debug = LTIEnvironment.getCustomParameter(Constants.DEBUG_CUSTOM_LTI_PARAMETER,
                        request) != null;

                // System.out.println("ID:" + userDao.findByUserCode(1));
                User user = userDao.findByUserName(username);
                user.setUsername(username);
                user.setFirstname(first_name);
                user.setSurname(last_name);
                user.setFullname(full_name);
                user.setEmail(email);
                user.setImage(user_image);
                userDao.save(user);

                Course course = courseDao.findByCourseKey(course_key);
                course.setTitle(course_label);
                course.setLang(locale);

                if (course.getId() <= 0) {
                    course.setCreated(new Timestamp(date.getTime()));
                    course.setCoursekey(course_key);
                }
                courseDao.save(course);

                UserCourse userCourse = userCourseDao.findByCourseCode(course.getId(), user.getId());
                userCourse.setIs_instructor(is_instructor);
                //TODO change it
                userCourse.setRole("admin");

                UserCourseId userCourseId = new UserCourseId(user, course);
                userCourse.setPk(userCourseId);

                userCourseDao.save(userCourse);

                Course courseRoom = courseDao.findByCourseKey(course_key);

                Room room = roomDao.findByRoomKey(resource_key);
                if (room == null) {
                    room = new Room();
                }
                room.setId_course(courseRoom);
                room.setLabel(resource_label);
                if (room.getId() <= 0) {
                    //if there is no room, create a new room and meeting room
                    room.setIs_blocked(false);
                    room.setKey(resource_key);
                    room.setReason_blocked(null);
                    roomDao.save(room);
                }

                session.setAttribute(Constants.ROOM_SESSION, room);
                //Steps to integrate with your applicationa
                //6. Check if username exists in system
                //6.1 If doesn't exist you have to create user using Tool Api
                //TODO create_user
                //6.2 If exists you can update the values of user (if you want)
                //TODO update_user
                //7. Check if course exists in system (you can set the locale of course)
                //7.1 If doesn't exist you have to create course using Tool Api
                //TODO create_course
                //7.2 If exists you can update the values of course (if you want)
                //TODO update_course
                //8. Register user in course 
                session.setAttribute(Constants.USER_SESSION, user);
                session.setAttribute(Constants.COURSE_SESSION, course);
                locale = locale.substring(0, 2);
                session.setAttribute(Constants.USER_LANGUAGE, locale);
                params = "?" + Constants.PARAM_SPRING_LANG + "=" + locale;
                nextPage = redirectToPlayer ? "searchMeeting" : "videochat";

            } else {

                Exception lastException = LTIEnvironment.getLastException();
                logger.error("Error authenticating user LTI Exception " + lastException);
                //Retornar excepcio
                nextPage = "errorLTI";
            }
        } else {
            logger.warn("Error authenticating user LTI is not LTI Request ");
            nextPage = "errorNoLTIRequest";
        }
    } catch (Exception e) {
        logger.error("Error authenticating user ", e);

    }
    response.sendRedirect(request.getContextPath() + "/" + nextPage + ".htm" + params);
}

From source file:com.openmeap.admin.web.servlet.WebViewServlet.java

public void init() {
    context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
}

From source file:org.vaadin.spring.servlet.Vaadin4SpringServlet.java

@Override
protected void servletInitialized() throws ServletException {
    super.servletInitialized();
    final WebApplicationContext applicationContext = WebApplicationContextUtils
            .getWebApplicationContext(getServletContext());
    try {// ww w .  j  a  va 2 s.  c om
        SystemMessagesProvider systemMessagesProvider = applicationContext
                .getBean(SystemMessagesProvider.class);
        LOGGER.info("Using custom SystemMessagesProvider {}", systemMessagesProvider);
        getService().setSystemMessagesProvider(systemMessagesProvider);
    } catch (BeansException ex) {
        LOGGER.info("Could not find a SystemMessagesProvider in the application context, using default");
    }
    for (SessionInitListener sessionInitListener : applicationContext.getBeansOfType(SessionInitListener.class)
            .values()) {
        LOGGER.info("Adding SessionInitListener {}", sessionInitListener);
        getService().addSessionInitListener(sessionInitListener);
    }
    for (SessionDestroyListener sessionDestroyListener : applicationContext
            .getBeansOfType(SessionDestroyListener.class).values()) {
        LOGGER.info("Adding SessionDestroyListener {}", sessionDestroyListener);
        getService().addSessionDestroyListener(sessionDestroyListener);
    }
    for (ServiceDestroyListener serviceDestroyListener : applicationContext
            .getBeansOfType(ServiceDestroyListener.class).values()) {
        LOGGER.info("Adding ServiceDestroyListener {}", serviceDestroyListener);
        getService().addServiceDestroyListener(serviceDestroyListener);
    }
    LOGGER.info("Custom Vaadin4Spring servlet initialization completed");
}