org.apache.wicket.ThreadContext Java Examples

The following examples show how to use org.apache.wicket.ThreadContext. 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: ApplicationHelper.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
public static IApplication ensureApplication() {
	if (Application.exists()) {
		return (IApplication)Application.get();
	}
	synchronized (SYNC_OBJ) {
		if (Application.exists()) {
			return (IApplication)Application.get();
		}
		WebApplication app = createApp((WebApplication)Application.get(getWicketApplicationName()));
		LabelDao.initLanguageMap();
		if (app != null) {
			if (!isInitComplete()) {
				initApp(app);
			}
			ThreadContext.setApplication(app);
		}
		return (IApplication)Application.get(getWicketApplicationName());
	}
}
 
Example #2
Source File: OSendMailTask.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
private void performTask(OSendMailTaskSessionRuntime runtime) {
    OrienteerWebSession session = OrienteerWebSession.get();
    OrienteerWebApplication app = OrienteerWebApplication.get();
    RequestCycle requestCycle = RequestCycle.get();

    new Thread(() -> {
        ThreadContext.setSession(session);
        ThreadContext.setApplication(app);
        ThreadContext.setRequestCycle(requestCycle);

        DBClosure.sudoConsumer(db -> {
            try {
                sendMails(runtime);
            } catch (Exception ex) {
                LOG.error("Error occurred during perform task {}", OSendMailTask.this, ex);
            } finally {
                runtime.finish();
            }
        });
    }).start();
}
 
Example #3
Source File: Application.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
public static String getString(String key, final Locale loc, String... _params) {
	if (!exists()) {
		ThreadContext.setApplication(org.apache.wicket.Application.get(appName));
	}
	String[] params = _params;
	if ((params == null || params.length == 0) && STRINGS_WITH_APP.contains(key)) {
		params = new String[]{getApplicationName()};
	}
	Localizer l = get().getResourceSettings().getLocalizer();
	String value = l.getStringIgnoreSettings(key, null, null, loc, null, "[Missing]");
	if (params != null && params.length > 0) {
		final MessageFormat format = new MessageFormat(value, loc);
		value = format.format(params);
	}
	if (RuntimeConfigurationType.DEVELOPMENT == get().getConfigurationType()) {
		value += String.format(" [%s]", key);
	}
	return value;
}
 
Example #4
Source File: ThreadHelper.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
public static void startRunnable(Runnable r, String name) {
	final Application app = Application.get();
	final WebSession session = WebSession.get();
	final RequestCycle rc = RequestCycle.get();
	Thread t = new Thread(() -> {
		ThreadContext.setApplication(app);
		ThreadContext.setSession(session);
		ThreadContext.setRequestCycle(rc);
		r.run();
		ThreadContext.detach();
	});
	if (!Strings.isEmpty(name)) {
		t.setName(name);
	}
	t.start();
}
 
Example #5
Source File: PersonalCookieManager.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
protected CookieManager getPersonalCookieManager()
{
	try
	{
		if(!ThreadContext.exists() || RequestCycle.get()==null) return defaultManager;
		
		OrientDbWebSession session = OrientDbWebSession.get();
		session.bind();
		String id = session.getId();
		if(session.isSignedIn()) id=session.getUsername()+'-'+id;
		return cache.get(id, new Callable<CookieManager>() {

			@Override
			public CookieManager call() throws Exception {
				return new CookieManager();
			}
		});
	} catch (ExecutionException e)
	{
		throw new IllegalStateException("Cookie Manager should be always calculated");
	}
}
 
Example #6
Source File: OMailServiceImpl.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Void> fetchMailsAsync(OMailSettings settings, String folderName, Consumer<Message> consumer) {
    OrienteerWebSession session = OrienteerWebSession.get();
    OrienteerWebApplication app = OrienteerWebApplication.get();
    RequestCycle requestCycle = RequestCycle.get();
    return CompletableFuture.runAsync(() -> {
        ThreadContext.setSession(session);
        ThreadContext.setApplication(app);
        ThreadContext.setRequestCycle(requestCycle);
        try {
            fetchMails(settings, folderName, consumer);
        } catch (Exception ex) {
            LOG.error("Error during fetching mails: {}", settings, ex);
        }
    });
}
 
Example #7
Source File: TopologyWebSocketBehavior.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public String call() throws Exception {
    ThreadContext.setApplication(application);
    ThreadContext.setSession(session);

    try {
        final ConnInstanceTO connector = ConnectorRestClient.read(key);
        return String.format("{ \"status\": \"%s\", \"target\": \"%s\"}",
                ConnectorRestClient.check(connector).getLeft()
                ? TopologyNode.Status.REACHABLE : TopologyNode.Status.UNREACHABLE, key);
    } catch (Exception e) {
        LOG.warn("Error checking connection for {}", key, e);
        return String.format("{ \"status\": \"%s\", \"target\": \"%s\"}",
                TopologyNode.Status.FAILURE, key);
    } finally {
        ThreadContext.detach();
    }
}
 
Example #8
Source File: TopologyWebSocketBehavior.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public String call() throws Exception {
    ThreadContext.setApplication(application);
    ThreadContext.setSession(session);

    try {
        final ResourceTO resource = ResourceRestClient.read(key);
        return String.format("{ \"status\": \"%s\", \"target\": \"%s\"}",
                ResourceRestClient.check(resource).getLeft()
                ? TopologyNode.Status.REACHABLE : TopologyNode.Status.UNREACHABLE, key);
    } catch (Exception e) {
        LOG.warn("Error checking connection for {}", key, e);
        return String.format("{ \"status\": \"%s\", \"target\": \"%s\"}",
                TopologyNode.Status.FAILURE,
                key);
    } finally {
        ThreadContext.detach();
    }
}
 
Example #9
Source File: TopologyWebSocketBehavior.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    ThreadContext.setApplication(application);
    ThreadContext.setSession(session);

    try {
        timeoutHandlingConnectionChecker(
                new ConnectorChecker(key, this.application),
                connectorTestTimeout,
                connectors,
                runningConnCheck);
    } finally {
        ThreadContext.detach();
    }
}
 
Example #10
Source File: ONotificationSendTask.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  OrienteerWebApplication app = OrienteerWebApplication.lookupApplication();
  INotificationService notificationService = app.getServiceInstance(INotificationService.class);
  ThreadContext.setApplication(app);

  DBClosure.sudoConsumer(db -> notificationService.send(notifications));
}
 
Example #11
Source File: OMailServiceImpl.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private void executeInNewThread(Runnable runnable) {
    OrienteerWebSession session = OrienteerWebSession.get();
    OrienteerWebApplication app = OrienteerWebApplication.get();
    RequestCycle requestCycle = RequestCycle.get();

    new Thread(() -> {
        ThreadContext.setSession(session);
        ThreadContext.setApplication(app);
        ThreadContext.setRequestCycle(requestCycle);
        runnable.run();
    }).start();
}
 
Example #12
Source File: AjaxWizard.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<Serializable, Serializable> call() throws Exception {
    try {
        ThreadContext.setApplication(this.application);
        ThreadContext.setRequestCycle(this.requestCycle);
        ThreadContext.setSession(this.session);
        return AjaxWizard.this.onApplyInternal(this.target);
    } finally {
        ThreadContext.detach();
    }
}
 
Example #13
Source File: TopologyWebSocketBehavior.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    ThreadContext.setApplication(application);
    ThreadContext.setSession(session);

    try {
        timeoutHandlingConnectionChecker(
                new ResourceChecker(key, this.application),
                resourceTestTimeout,
                resources,
                runningResCheck);
    } finally {
        ThreadContext.detach();
    }
}
 
Example #14
Source File: ApplicationHelper.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public static void destroyApplication() {
	WebApplication app = (WebApplication)Application.get(getWicketApplicationName());
	WebApplicationContext ctx = getWebApplicationContext(app.getServletContext());
	app.internalDestroy(); //need to be called too
	if (ctx != null) {
		((XmlWebApplicationContext)ctx).close();
	}
	ThreadContext.setApplication(null);
	ThreadContext.setRequestCycle(null);
	ThreadContext.setSession(null);
}
 
Example #15
Source File: ApplicationHelper.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public static IApplication ensureApplication(Long langId) {
	IApplication a = ensureApplication();
	if (ThreadContext.getRequestCycle() == null) {
		ServletWebRequest req = new ServletWebRequest(new MockHttpServletRequest((Application)a, new MockHttpSession(a.getServletContext()), a.getServletContext()), "");
		RequestCycleContext rctx = new RequestCycleContext(req, new MockWebResponse(), a.getRootRequestMapper(), a.getExceptionMapperProvider().get());
		ThreadContext.setRequestCycle(new RequestCycle(rctx));
	}
	if (ThreadContext.getSession() == null) {
		WebSession s = WebSession.get();
		if (langId > 0) {
			((IWebSession)s).setLanguage(langId);
		}
	}
	return a;
}
 
Example #16
Source File: ApplicationHelper.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
private static WebApplication initApp(WebApplication app) {
	if (app != null) {
		try {
			app.getServletContext();
		} catch(IllegalStateException e) {
			app.setServletContext(new MockServletContext(app, null));
		}
		app.setConfigurationType(RuntimeConfigurationType.DEPLOYMENT);
		OMContextListener omcl = new OMContextListener();
		omcl.contextInitialized(new ServletContextEvent(app.getServletContext()));
		ThreadContext.setApplication(app);
		app.initApplication();
	}
	return app;
}
 
Example #17
Source File: AbstractWebSocketProcessor.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Exports the Wicket thread locals and broadcasts the received message from the client to all
 * interested components and behaviors in the page with id {@code #pageId}
 * <p>
 *     Note: ConnectedMessage and ClosedMessage messages are notification-only. I.e. whatever the
 *     components/behaviors write in the WebSocketRequestHandler will be ignored because the protocol
 *     doesn't expect response from the user.
 * </p>
 *
 * @param message
 *      the message to broadcast
 */
public final void broadcastMessage(final IWebSocketMessage message)
{
	IKey key = getRegistryKey();
	IWebSocketConnection connection = connectionRegistry.getConnection(application, sessionId, key);

	if (connection != null && connection.isOpen())
	{
		Application oldApplication = ThreadContext.getApplication();
		Session oldSession = ThreadContext.getSession();
		RequestCycle oldRequestCycle = ThreadContext.getRequestCycle();

		WebResponse webResponse = webSocketSettings.newWebSocketResponse(connection);
		try
		{
			WebSocketRequestMapper requestMapper = new WebSocketRequestMapper(application.getRootRequestMapper());
			RequestCycle requestCycle = createRequestCycle(requestMapper, webResponse);
			ThreadContext.setRequestCycle(requestCycle);

			ThreadContext.setApplication(application);

			Session session;
			if (oldSession == null || message instanceof IWebSocketPushMessage)
			{
				ISessionStore sessionStore = application.getSessionStore();
				session = sessionStore.lookup(webRequest);
				ThreadContext.setSession(session);
			}
			else
			{
				session = oldSession;
			}

			// Session is null if we copy the url with jsessionid to a new browser window 
			if (session != null) {
				IPageManager pageManager = session.getPageManager();
				Page page = getPage(pageManager);

				if (page != null) {
					WebSocketRequestHandler requestHandler = webSocketSettings.newWebSocketRequestHandler(page, connection);

					@SuppressWarnings("rawtypes")
					WebSocketPayload payload = createEventPayload(message, requestHandler);

					if (!(message instanceof ConnectedMessage || message instanceof ClosedMessage))
					{
						requestCycle.scheduleRequestHandlerAfterCurrent(requestHandler);
					}

					IRequestHandler broadcastingHandler = new WebSocketMessageBroadcastHandler(pageId, resourceName, payload);
					requestMapper.setHandler(broadcastingHandler);
					requestCycle.processRequestAndDetach();
				}
			}
		}
		catch (Exception x)
		{
			try {
				connection.sendMessage(WebSocketManager.ERROR_MESSAGE);
			} catch (IOException e1) {
			}
			LOG.error("An error occurred during processing of a WebSocket message", x);
		}
		finally
		{
			try
			{
				webResponse.close();
			}
			finally
			{
				ThreadContext.setApplication(oldApplication);
				ThreadContext.setRequestCycle(oldRequestCycle);
				ThreadContext.setSession(oldSession);
			}
		}
	}
	else
	{
		LOG.debug("Either there is no connection({}) or it is closed.", connection);
	}
}