Java Code Examples for org.springframework.web.context.support.WebApplicationContextUtils#getWebApplicationContext()

The following examples show how to use org.springframework.web.context.support.WebApplicationContextUtils#getWebApplicationContext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ComOnePixelCount.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get the actionid to be executed on opening the mailing.
 * If the action id > 0, execute the action with parameters from the request.
 * 
 * @param uid
 *            ExtensibleUID object, contains parsed data from the "uid"
 *            request parameter
 * @param req
 *            HTTP request
 * @throws Exception
 */
protected void executeMailingOpenAction(final ComExtensibleUID uid, final HttpServletRequest req) throws Exception {
	int companyID = uid.getCompanyID();
	int mailingID = uid.getMailingID();
	int customerID = uid.getCustomerID();
	int openActionID = getMailingDao().getMailingOpenAction(mailingID, companyID);
	if (openActionID != 0) {
		EmmAction emmAction = getActionDao().getEmmAction(openActionID, companyID);
		if (emmAction != null) {
			final EmmActionOperationErrors actionOperationErrors = new EmmActionOperationErrors();

			// execute configured actions
			CaseInsensitiveMap<String, Object> params = new CaseInsensitiveMap<>();
			params.put("requestParameters", AgnUtils.getReqParameters(req));
			params.put("_request", req);
			params.put("customerID", customerID);
			params.put("mailingID", mailingID);
			params.put("actionErrors", actionOperationErrors);
			
			ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
			EmmActionService emmActionService = (EmmActionService) applicationContext.getBean("EmmActionService");
			emmActionService.executeActions(openActionID, companyID, params, actionOperationErrors);
		}
	}
}
 
Example 2
Source File: GetTestCaseList.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ITestCaseService testService = appContext.getBean(ITestCaseService.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    String test = policy.sanitize(httpServletRequest.getParameter("test"));
    JSONArray array = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    for (TestCase testcase : testService.findTestCaseByTest(test)) {
        array.put(testcase.getTestCase());
    }
    try {
        jsonObject.put("testcasesList", array);

        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().print(jsonObject.toString());
    } catch (JSONException exception) {
        LOG.warn(exception.toString());
    }
}
 
Example 3
Source File: DefaultMockMvcBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected WebApplicationContext initWebAppContext() {
	ServletContext servletContext = this.webAppContext.getServletContext();
	Assert.state(servletContext != null, "No ServletContext");
	ApplicationContext rootWac = WebApplicationContextUtils.getWebApplicationContext(servletContext);

	if (rootWac == null) {
		rootWac = this.webAppContext;
		ApplicationContext parent = this.webAppContext.getParent();
		while (parent != null) {
			if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) {
				rootWac = parent;
				break;
			}
			parent = parent.getParent();
		}
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, rootWac);
	}

	return this.webAppContext;
}
 
Example 4
Source File: CoreSpringFactory.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Prototype-method : Get service which is annotated with '@Service'.
 * 
 * @param <T>
 * @param serviceType
 * @return Service of requested type, must not be casted.
 * @throws RuntimeException
 *             when more than one service of the same type is registered. RuntimeException when servie is not annotated with '@Service'.
 * 
 *             *******not yet in use********
 */
private static <T> T getService(Class<T> serviceType) {
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
    Map<String, T> m = context.getBeansOfType(serviceType);
    if (m.size() > 1) {
        throw new OLATRuntimeException("found more than one service for: " + serviceType + ". Calling this method should only find one service-bean!", null);
    }
    T service = context.getBean(serviceType);
    Map<String, ?> services = context.getBeansWithAnnotation(org.springframework.stereotype.Service.class);
    if (services.containsValue(service)) {
        return service;
    } else {
        throw new OLATRuntimeException("Try to get Service which is not annotated with '@Service', services must have '@Service'", null);
    }
}
 
Example 5
Source File: UpdateMyUserRobotPreference.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IUserService userService = appContext.getBean(UserService.class);
    
    try {
                       
        String ss_ip = ParameterParserUtil.parseStringParam(request.getParameter("ss_ip"), "");
        String ss_p = ParameterParserUtil.parseStringParam(request.getParameter("ss_p"), "");
        String platform = ParameterParserUtil.parseStringParam(request.getParameter("platform"), "");
        String browser = ParameterParserUtil.parseStringParam(request.getParameter("browser"), "");
        String version = ParameterParserUtil.parseStringParam(request.getParameter("version"), "");

        User usr = userService.findUserByKey(request.getUserPrincipal().getName());
        usr.setRobotHost(ss_ip);
        usr.setRobotPort(ss_p);
        usr.setRobotPlatform(platform);
        usr.setRobotBrowser(browser);
        usr.setRobotVersion(version);
                        
        userService.updateUser(usr);
        
        ILogEventService logEventService = appContext.getBean(LogEventService.class);
        logEventService.createForPrivateCalls("/UpdateMyUserRobotPreference", "UPDATE", "Update user robot preference for user: " + usr.getLogin(), request);

        response.getWriter().print(usr.getLogin());
    } catch (CerberusException myexception) {
        response.getWriter().print(myexception.getMessageError().getDescription());
    }
}
 
Example 6
Source File: DownloadComponent.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void init() throws ServletException {
    super.init();

    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    this.userActivityLogService = ctx.getBean(UserActivityLogService.class);
}
 
Example 7
Source File: ComRdirUserForm.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private ComRecipientDao getRecipientDao() {
	if (comRecipientDao == null) {
		ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		comRecipientDao = (ComRecipientDao) applicationContext.getBean("RecipientDao");
	}
	return comRecipientDao;
}
 
Example 8
Source File: DbFileServlet.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void init() throws ServletException {
	WebApplicationContext appCtx = WebApplicationContextUtils
			.getWebApplicationContext(getServletContext());
	dbFileMng = BeanFactoryUtils.beanOfTypeIncludingAncestors(appCtx,
			DbFileMng.class);
}
 
Example 9
Source File: ServerListener.java    From sds with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent event) {
    springContext = WebApplicationContextUtils
            .getWebApplicationContext(event.getServletContext());
    initService = springContext.getBean(InitService.class);
    initService.start();

}
 
Example 10
Source File: RebuildBindingHistoryTriggersOnStartupListener.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public final void contextInitialized(final ServletContextEvent servletContextEvent) {
	final ServletContext servletContext = servletContextEvent.getServletContext();
	webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);

	updateMarkedCompanies();
}
 
Example 11
Source File: AutoLoginFilter.java    From sdudoc with MIT License 5 votes vote down vote up
@Override
public void init(FilterConfig filterConfig) throws ServletException {
	log.info("AutoLoginFilter Init");
	//使用以下方式来完成userService的注入
	ServletContext context = filterConfig.getServletContext();
	ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
	userService = (UserService) ctx.getBean("userService");
}
 
Example 12
Source File: SsoHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected ILogEventService getLogEventService(ServletContext context) {
if (SsoHandler.logEventService == null) {
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
    SsoHandler.logEventService = (ILogEventService) ctx.getBean("logEventService");
}
return SsoHandler.logEventService;
   }
 
Example 13
Source File: DeleteDeployType.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    
    /**
     * Parsing and securing all required parameters.
     */
    String key = policy.sanitize(request.getParameter("deploytype"));

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(key)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Deploy Type")
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "Deployement Type ID (deploytype) is missing."));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IDeployTypeService deployTypeService = appContext.getBean(IDeployTypeService.class);

        AnswerItem resp = deployTypeService.readByKey(key);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem()!=null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Deploy Type")
                    .replace("%OPERATION%", "Delete")
                    .replace("%REASON%", "Deploy Type does not exist."));
            ans.setResultMessage(msg);

        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can delete it.
             */
            DeployType deployTypeData = (DeployType) resp.getItem();
            ans = deployTypeService.delete(deployTypeData);

            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Delete was successful. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/DeleteDeployType", "DELETE", "Delete Deploy Type : ['" + key + "']", request);
            }
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse.toString());
    response.getWriter().flush();

}
 
Example 14
Source File: WebMvcMetricsFilter.java    From foremast with Apache License 2.0 4 votes vote down vote up
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());

    this.registry = ctx.getBean(MeterRegistry.class);
    this.metricsProperties = ctx.getBean(MetricsProperties.class);
    this.metricName = metricsProperties.getWeb().getServer().getRequestsMetricName();
    this.autoTimeRequests = metricsProperties.getWeb().getServer().isAutoTimeRequests();
    this.mappingIntrospector = new HandlerMappingIntrospector(ctx);

    String path = filterConfig.getInitParameter("prometheus-path");
    if (path != null) {
        exposePrometheus = true;
        this.prometheusPath = path;
    }

    if (exposePrometheus) {
        prometheusServlet = new PrometheusServlet();
        prometheusServlet.init(new ServletConfig() {
            @Override
            public String getServletName() {
                return "prometheus";
            }

            @Override
            public ServletContext getServletContext() {
                return filterConfig.getServletContext();
            }

            @Override
            public String getInitParameter(String s) {
                return filterConfig.getInitParameter(s);
            }

            @Override
            public Enumeration getInitParameterNames() {
                return filterConfig.getInitParameterNames();
            }
        });
    }

    //Tomcat
    try {
        new TomcatMetrics(null, Collections.emptyList()).bindTo(this.registry);
    }
    catch(Throwable tx) {

    }
}
 
Example 15
Source File: DeleteTestCase.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, JSONException, CerberusException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    
    /**
     * Parsing and securing all required parameters.
     */
    String test = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("test"), "");
    String testCase = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("testCase"), null);

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(test) || testCase == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCase")
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "mendatory fields is missing!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ITestCaseService testCaseService = appContext.getBean(ITestCaseService.class);
        ITestCaseStepService testCaseStepService = appContext.getBean(ITestCaseStepService.class);

        AnswerItem resp = testCaseService.readByKey(test, testCase);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem()!=null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCase")
                    .replace("%OPERATION%", "Delete")
                    .replace("%REASON%", "TestCase does not exist."));
            ans.setResultMessage(msg);

        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can delete it.
             */
            TestCase testCaseData = (TestCase) resp.getItem();
            List<TestCaseStep> tcsList = testCaseStepService.getTestCaseStepUsingTestCaseInParamter(testCaseData.getTest(), testCaseData.getTestCase());
            if (tcsList != null && !tcsList.isEmpty()) {
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
                msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCase")
                        .replace("%OPERATION%", "Delete")
                        .replace("%REASON%", "You're trying to delete a testcase which have some step used in other tests. Please remove the link before deleting this testcase."));
                ans.setResultMessage(msg);
            } else {
                ans = testCaseService.delete(testCaseData);
            }

            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Delete was successful. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/DeleteTestCase", "DELETE", "Delete TestCase : ['" + test + "'|'" + testCase + "']", request);
            }
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse.toString());
    response.getWriter().flush();
}
 
Example 16
Source File: InitSQLData.java    From init-spring with Apache License 2.0 4 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    WebApplicationContext webApplicationContext =
            WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
    PersonRepository personRepository = webApplicationContext.getBean(PersonRepository.class);
    personRepository.deleteAll();

    List<Person> personList = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        String chars = "abcdefghijklmnopqrstuvwxyz";
        String name = String.valueOf(chars.charAt((int) (Math.random() * 26)));
        Person person = new Person();
        person.setName(name);
        person.setAge((i % 100) + 1);
        personList.add(person);
    }
    personRepository.save(personList);

    UserRepository userRepository = webApplicationContext.getBean(UserRepository.class);
    userRepository.deleteAll();

    User user = new User();
    user.setName("[email protected]");
    byte[] passwordSalt = UUID.randomUUID().toString().getBytes();
    user.setPasswordSalt(passwordSalt);
    user.setPassword("123");
    String passwordHash =
            new Sha512Hash(user.getPassword(), user.getName() + new String(passwordSalt), 99)
                    .toString();
    user.setPasswordHash(passwordHash);

    RoleRepository roleRepository = webApplicationContext.getBean(RoleRepository.class);
    roleRepository.deleteAll();
    Set<Role> roleSet = new HashSet<>();
    Role role = new Role();
    role.setName("admin");
    role.setDescription("管理员");

    List<String> permissisonList = new ArrayList<>();
    permissisonList.add("user:view");
    permissisonList.add("role:view");
    role.setPermissions(permissisonList);
    roleSet.add(roleRepository.save(role));
    user.setRoles(roleSet);
    userRepository.save(user);


}
 
Example 17
Source File: TargetForm.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void loadNonFormDataForErrorView(ActionMapping mapping, HttpServletRequest request) {
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
    addMailings(request, (MailingDao) context.getBean("MailingDao"), (TrackableLinkDao) context.getBean("TrackableLinkDao"));
}
 
Example 18
Source File: ApsWebApplicationUtils.java    From entando-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static WebApplicationContext getWebApplicationContext(ServletContext svCtx) {
	return WebApplicationContextUtils.getWebApplicationContext(svCtx);
}
 
Example 19
Source File: UpdateTodoServlet.java    From RealWorldWebApplicationWithServletsAndJspIn28Minutes with MIT License 3 votes vote down vote up
@Override
public void init(ServletConfig servletConfig) throws ServletException {

	ApplicationContext applicationContext = WebApplicationContextUtils
			.getWebApplicationContext(servletConfig.getServletContext());

	todoService = applicationContext.getBean(TodoService.class);

	resourceBundle = ResourceBundle.getBundle("todolist");
}
 
Example 20
Source File: ApplicationContextUtil.java    From geomajas-project-server with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Get the Geomajas application context.
 *
 * @param servletContext servlet context
 * @return application config
 */
public static ApplicationContext getApplicationContext(ServletContext servletContext) {
	return WebApplicationContextUtils.getWebApplicationContext(servletContext);
}