org.apache.wicket.request.IRequestHandler Java Examples

The following examples show how to use org.apache.wicket.request.IRequestHandler. 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: RestartResponseAtInterceptPageException.java    From onedev with MIT License 6 votes vote down vote up
@Override
public IRequestHandler mapRequest(Request request)
{
	InterceptData data = matchedData(request);
	if (data != null)
	{
		if (data.postParameters.isEmpty() == false &&
			request.getPostParameters() instanceof IWritableRequestParameters)
		{
			IWritableRequestParameters parameters = (IWritableRequestParameters)request.getPostParameters();
			parameters.reset();
			for (String s : data.postParameters.keySet())
			{
				parameters.setParameterValues(s, data.postParameters.get(s));
			}
		}
		InterceptData.clear();
	}
	return null;
}
 
Example #2
Source File: NextServerApplication.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
@Override
public IRequestHandler onException(RequestCycle cycle, Exception e) {
	if (e instanceof PageExpiredException) {
		LOG.error("Page expired", e); // !?
		return null; // see
						// getApplicationSettings().setPageExpiredErrorPage
	}

	if (e instanceof MaintenanceException) {
		return new RenderPageRequestHandler(new PageProvider(MaintenancePage.class));
	}

	if (e instanceof StalePageException) {
		return null;
	}

	String errorCode = String.valueOf(System.currentTimeMillis());
	LOG.error("Error with code " + errorCode, e);

	PageParameters parameters = new PageParameters();
	parameters.add("errorCode", errorCode);
	parameters.add("errorMessage", UrlEncoder.QUERY_INSTANCE.encode(e.getMessage(), HTTP.ISO_8859_1));
	return new RenderPageRequestHandler(new PageProvider(ErrorPage.class, parameters));
}
 
Example #3
Source File: AbstractMountedMapper.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that request is for this mapper
 * @param requestHandler request handler for handle request
 * @return url if this mapper can handle this request
 */
@Override
public Url mapHandler(IRequestHandler requestHandler) {
    if (requestHandler instanceof IPageClassRequestHandler) {
        IPageClassRequestHandler handler = (IPageClassRequestHandler) requestHandler;
        PageParameters params = null;
        if (handler instanceof IPageRequestHandler) {
            IRequestablePage page = ((IPageRequestHandler)handler).getPage();
            if (page != null) {
                params = page.getPageParameters();
            }
        }

        if (params == null) {
            params = handler.getPageParameters();
        }
        return isMatch(params) ? super.mapHandler(requestHandler) : null;
    } else {
        return super.mapHandler(requestHandler);
    }
}
 
Example #4
Source File: OrientDefaultExceptionsHandlingListener.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
private Page extractCurrentPage(boolean fullSearch)
{
	final RequestCycle requestCycle = RequestCycle.get();

	IRequestHandler handler = requestCycle.getActiveRequestHandler();

	if (handler == null)
	{
		handler = requestCycle.getRequestHandlerScheduledAfterCurrent();
		
		if(handler==null && fullSearch) {
			handler = OrientDbWebApplication.get().getRootRequestMapper().mapRequest(requestCycle.getRequest());
		}
	}

	if (handler instanceof IPageRequestHandler)
	{
		IPageRequestHandler pageRequestHandler = (IPageRequestHandler)handler;
		return (Page)pageRequestHandler.getPage();
	}
	return null;
}
 
Example #5
Source File: AbstractContentAwareTransactionRequestCycleListener.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
public void onRequestHandlerResolved(RequestCycle cycle,
		IRequestHandler handler) {
	if(isInProgress(cycle)) return;
	if(isOurContent(cycle, handler))
	{
		setInProgress(cycle, true);
		start(cycle);
	}
}
 
Example #6
Source File: NoVersionMountMapper.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
@Override
public Url mapHandler(IRequestHandler requestHandler) {
    if (requestHandler instanceof ListenerInterfaceRequestHandler || 
    	requestHandler instanceof BookmarkableListenerInterfaceRequestHandler) {
        return null;
    } else {
        return super.mapHandler(requestHandler);
    }
}
 
Example #7
Source File: OpenFlashChart.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
@Override
	public void onResourceRequested() {
		//System.out.println("OpenFlashChart.onResourceRequested()");
		//System.out.println("requestUrl = " + RequestCycle.get().getRequest().getUrl());
		//System.out.println("... " + this);
		IResource jsonResource = createJsonResource();
//		IResource.Attributes attrs = new IResource.Attributes(RequestCycle.get().getRequest(), RequestCycle.get().getResponse(), null);
//		jsonResource.respond(attrs);
		IRequestHandler requestHandler = new ResourceRequestHandler(jsonResource, null);
		requestHandler.respond(getRequestCycle());
	}
 
Example #8
Source File: OMetricsRequestCycleListener.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void onRequestHandlerExecuted(RequestCycle cycle, IRequestHandler handler) {
	String ajaxLabel = Boolean.toString(((WebRequest)cycle.getRequest()).isAjax());
	COUNTER_EXECUTIONS.labels(ajaxLabel,
								handler.getClass().getSimpleName()).inc();
	if(handler instanceof IPageClassRequestHandler) {
		COUNTER_PAGES.labels(ajaxLabel,
				((IPageClassRequestHandler)handler).getPageClass().getSimpleName()).inc();
	}
}
 
Example #9
Source File: AcademicSessionAdminApplication.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
protected void init() {
	
	//Configure for Spring injection
    getComponentInstantiationListeners().add(new SpringComponentInjector(this));
	
	
	//Don't throw an exception if we are missing a property, just fallback
	getResourceSettings().setThrowExceptionOnMissingResource(false);
	
	//Remove the wicket specific tags from the generated markup
	getMarkupSettings().setStripWicketTags(true);
			
	// On Wicket session timeout, redirect to main page
	getApplicationSettings().setPageExpiredErrorPage(getHomePage());
	getApplicationSettings().setAccessDeniedPage(getHomePage());
	

	
	getRequestCycleListeners().add(new AbstractRequestCycleListener() {
		@Override
		 public IRequestHandler onException(RequestCycle cycle, Exception ex) {
			 if (ex instanceof RuntimeException) {
				 RuntimeException re = (RuntimeException)ex;
				 throw re;
			 }
			 return super.onException(cycle, ex);
		}
	});
	
}
 
Example #10
Source File: TransactionRequestCycleListener.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isOurContent(RequestCycle cycle, IRequestHandler handler) {
	if(handler instanceof ResourceReferenceRequestHandler)
	{
		ResourceReferenceRequestHandler rrrHandler = (ResourceReferenceRequestHandler)handler;
		ResourceReference reference = rrrHandler.getResourceReference();
		return !(reference instanceof PackageResourceReference);
	}
	return true;
}
 
Example #11
Source File: OrientDefaultExceptionsHandlingListener.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
public IRequestHandler onException(RequestCycle cycle, Exception ex) {
	try {
		Throwable th = null;
		if((th=Exceptions.findCause(ex, OSecurityException.class))!=null
				|| (th=Exceptions.findCause(ex, OValidationException.class))!=null
				|| (th=Exceptions.findCause(ex, OSchemaException.class))!=null
				|| (th=Exceptions.findCause(ex, IllegalStateException.class))!=null && Exceptions.findCause(ex, WicketRuntimeException.class)==null)
		{
			Page page = extractCurrentPage(false);
			if(page==null) {
				if(th instanceof OSecurityException) 
					OrientDbWebApplication.get().restartResponseAtSignInPage(); //Will throw exception
				return null;
			}
			OrientDbWebSession.get().error(th.getMessage());
			return new RenderPageRequestHandler(new PageProvider(page),
			RenderPageRequestHandler.RedirectPolicy.ALWAYS_REDIRECT);
		}
		else if((th=Exceptions.findCause(ex, UnauthorizedActionException.class))!=null)
		{
			final UnauthorizedActionException unauthorizedActionException = (UnauthorizedActionException)th;
			return new UnauthorizedInstantiationHandler(unauthorizedActionException.getComponent());
		}
		else
		{
			return null;
		}
	} catch (ReplaceHandlerException e) {
		return e.getReplacementRequestHandler();
	}
}
 
Example #12
Source File: LazyAuthorizationRequestCycleListener.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
public void onRequestHandlerResolved(RequestCycle cycle,
		IRequestHandler handler) {
	Boolean lazyAuthorized = cycle.getMetaData(LAZY_AUTHORIZED);
	if(lazyAuthorized!=null && !lazyAuthorized)
	{
		cycle.setMetaData(LAZY_AUTHORIZED, null);
		throw new LazyAuthorizationException();
	}
}
 
Example #13
Source File: AppendLoadingIndicatorListener.java    From onedev with MIT License 5 votes vote down vote up
@Override
public CharSequence getBeforeSendHandler(Component component) {
	IRequestHandler handler = new ResourceReferenceRequestHandler(
			AbstractPostAjaxBehavior.INDICATOR);
	CharSequence url = RequestCycle.get().urlFor(handler);
	return String.format(""
			+ "$('#%s-working-indicator').remove(); "
			+ "$('#%s').after('<img id=\"%s-working-indicator\" src=\"%s\" class=\"working-indicator\"></img>');", 
			component.getMarkupId(), component.getMarkupId(), component.getMarkupId(), url);
}
 
Example #14
Source File: OneWebApplication.java    From onedev with MIT License 5 votes vote down vote up
@Override
public final IProvider<IExceptionMapper> getExceptionMapperProvider() {
	return new IProvider<IExceptionMapper>() {

		@Override
		public IExceptionMapper get() {
			return new DefaultExceptionMapper() {

				@Override
				protected IRequestHandler mapExpectedExceptions(Exception e, Application application) {
					RequestCycle requestCycle = RequestCycle.get();
					boolean isAjax = ((WebRequest)requestCycle.getRequest()).isAjax();
					if (isAjax && (e instanceof ListenerInvocationNotAllowedException || e instanceof ComponentNotFoundException))
						return EmptyAjaxRequestHandler.getInstance();
					
					IRequestMapper mapper = Application.get().getRootRequestMapper();
					if (mapper.mapRequest(requestCycle.getRequest()) instanceof ResourceReferenceRequestHandler)
						return new ResourceErrorRequestHandler(e);
					
					HttpServletResponse response = (HttpServletResponse) requestCycle.getResponse().getContainerResponse();
					if (!response.isCommitted()) {
						InUseException inUseException = ExceptionUtils.find(e, InUseException.class);
						if (inUseException != null)
							return createPageRequestHandler(new PageProvider(new InUseErrorPage(inUseException)));
						else
							return createPageRequestHandler(new PageProvider(new GeneralErrorPage(e)));
					} else {
						return super.mapExpectedExceptions(e, application);
					}
				}
				
			};
		}
		
	};
}
 
Example #15
Source File: StorefrontRequestCycleListener.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public IRequestHandler onException(final RequestCycle cycle, final Exception ex) {
    if (ex instanceof SeoEntryIdInvalidException)  {
        LOG.error(ex.getMessage());
        return new RedirectRequestHandler("/"); //TODO: add more sophisticated error handling if require
    }
    return null;
}
 
Example #16
Source File: AcademicSessionAdminApplication.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
protected void init() {
	
	//Configure for Spring injection
    getComponentInstantiationListeners().add(new SpringComponentInjector(this));
	
	
	//Don't throw an exception if we are missing a property, just fallback
	getResourceSettings().setThrowExceptionOnMissingResource(false);
	
	//Remove the wicket specific tags from the generated markup
	getMarkupSettings().setStripWicketTags(true);
			
	// On Wicket session timeout, redirect to main page
	getApplicationSettings().setPageExpiredErrorPage(getHomePage());
	getApplicationSettings().setAccessDeniedPage(getHomePage());
	

	
	getRequestCycleListeners().add(new AbstractRequestCycleListener() {
		@Override
		 public IRequestHandler onException(RequestCycle cycle, Exception ex) {
			 if (ex instanceof RuntimeException) {
				 RuntimeException re = (RuntimeException)ex;
				 throw re;
			 }
			 return super.onException(cycle, ex);
		}
	});
	
}
 
Example #17
Source File: Application.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
@Override
public Url mapHandler(IRequestHandler requestHandler) {
	if (requestHandler instanceof ListenerRequestHandler || requestHandler instanceof BookmarkableListenerRequestHandler) {
		return null;
	} else {
		return super.mapHandler(requestHandler);
	}
}
 
Example #18
Source File: ProfileApplication.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public IRequestHandler onException(final RequestCycle cycle, final Exception ex) {
	return null;
}
 
Example #19
Source File: RestartResponseAtInterceptPageException.java    From onedev with MIT License 4 votes vote down vote up
@Override
public Url mapHandler(IRequestHandler requestHandler)
{
	return null;
}
 
Example #20
Source File: BasicResourceReferenceMapper.java    From onedev with MIT License 4 votes vote down vote up
@Override
public IRequestHandler mapRequest(Request request)
{
	Url url = request.getUrl();

	if (canBeHandled(url))
	{
		final int segmentsSize = url.getSegments().size();

		// extract the PageParameters from URL if there are any
		PageParameters pageParameters = extractPageParameters(request, segmentsSize,
				pageParametersEncoder);

		String normalizedClassName = url.getSegments().get(2);
		String className = classNames.get(normalizedClassName);
		if (className == null)
			className = normalizedClassName;
		StringBuilder name = new StringBuilder(segmentsSize * 2);

		for (int i = 3; i < segmentsSize; ++i)
		{
			String segment = url.getSegments().get(i);

			// ignore invalid segments
			if (segment.indexOf('/') > -1)
			{
				return null;
			}

			// remove caching information
			if (i + 1 == segmentsSize && Strings.isEmpty(segment) == false)
			{
				// The filename + parameters eventually contain caching
				// related information which needs to be removed
				ResourceUrl resourceUrl = new ResourceUrl(segment, pageParameters);
				getCachingStrategy().undecorateUrl(resourceUrl);
				segment = resourceUrl.getFileName();

				Checks.notEmpty(segment, "Caching strategy returned empty name for '%s'", resourceUrl);
			}
			if (name.length() > 0)
			{
				name.append('/');
			}
			name.append(segment);
		}

		ResourceReference.UrlAttributes attributes = ResourceUtil.decodeResourceReferenceAttributes(url);

		Class<?> scope = resolveClass(className);

		if (scope != null && scope.getPackage() != null)
		{
			ResourceReference res = getContext().getResourceReferenceRegistry()
				.getResourceReference(scope, name.toString(), attributes.getLocale(),
					attributes.getStyle(), attributes.getVariation(), true, true);

			if (res != null)
			{
				return new ResourceReferenceRequestHandler(res, pageParameters);
			}
		}
	}
	return null;
}
 
Example #21
Source File: PageParameterAwareMountedMapper.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected IRequestHandler processHybrid(PageInfo pageInfo, Class< ? extends IRequestablePage> pageClass, PageParameters pageParameters,
    Integer renderCount)
{
  IRequestHandler handler = null;
  try {
    handler = super.processHybrid(pageInfo, pageClass, pageParameters, renderCount);
  } catch (PageExpiredException e) {
    // in case of pageExpiredException at this point, we just redirect to previous bookmarkable resource
    return processBookmarkable(pageClass, pageParameters);
  }
  if (handler != null && handler instanceof RenderPageRequestHandler) {
    // in the current implementation (wicket 1.5.6) super.processHybrid
    // returns a RenderPageRequestHandler
    RenderPageRequestHandler renderPageHandler = (RenderPageRequestHandler) handler;
    if (renderPageHandler.getPageProvider() instanceof PageProvider) {
      PageProvider provider = (PageProvider) renderPageHandler.getPageProvider();
      // This check is necessary to prevent a RestartResponseAtInterceptPageException at the wrong time in request cycle
      if (provider.hasPageInstance()) {
        // get page classes
        Class< ? extends IRequestablePage> oldPageClass = renderPageHandler.getPageClass();
        Class< ? extends IRequestablePage> newPageClass = renderPageHandler.getPageProvider().getPageClass();

        // get page parameters
        PageParameters newPageParameters = renderPageHandler.getPageParameters();
        PageParameters oldPageParameters = renderPageHandler.getPageProvider().getPageInstance().getPageParameters();

        if (oldPageClass != null && oldPageClass.equals(newPageClass) == false) {
          return processBookmarkable(newPageClass, newPageParameters);
        }

        // if we recognize a change between the page parameter of the loaded
        // page and the page parameter of the current request, we redirect
        // to a fresh bookmarkable instance of that page.
        if (!PageParameters.equals(oldPageParameters, newPageParameters)) {
          return processBookmarkable(newPageClass, newPageParameters);
        }
      }
    }
  }
  return handler;
}
 
Example #22
Source File: OMetricsRequestCycleListener.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
@Override
public IRequestHandler onException(RequestCycle cycle, Exception ex) {
	COUNTER_EXCEPTIONS.labels(Boolean.toString(((WebRequest)cycle.getRequest()).isAjax())).inc();
	return null;
}
 
Example #23
Source File: OLoggerExceptionListener.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
@Override
public IRequestHandler onException(RequestCycle cycle, Exception ex) {
	OLogger.log(ex);
	return null;
}
 
Example #24
Source File: GradebookNgApplication.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public void init() {
	super.init();

	// page mounting for bookmarkable URLs
	mountPage("/grades", GradebookPage.class);
	mountPage("/settings", SettingsPage.class);
	mountPage("/importexport", ImportExportPage.class);
	mountPage("/permissions", PermissionsPage.class);
	mountPage("/gradebook", StudentPage.class);
	mountPage("/accessdenied", AccessDeniedPage.class);
	mountPage("/error", ErrorPage.class);

	// remove the version number from the URL so that browser refreshes re-render the page
	getRequestCycleSettings().setRenderStrategy(RenderStrategy.ONE_PASS_RENDER);

	// Configure for Spring injection
	getComponentInstantiationListeners().add(new SpringComponentInjector(this));

	// Add ResourceLoader that integrates with Sakai's Resource Loader
	getResourceSettings().getStringResourceLoaders().add(0, new GradebookNgStringResourceLoader());

	// Don't throw an exception if we are missing a property, just fallback
	getResourceSettings().setThrowExceptionOnMissingResource(false);

	// Remove the wicket specific tags from the generated markup
	getMarkupSettings().setStripWicketTags(true);

	// Don't add any extra tags around a disabled link (default is <em></em>)
	getMarkupSettings().setDefaultBeforeDisabledLink(null);
	getMarkupSettings().setDefaultAfterDisabledLink(null);

	// On Wicket session timeout, redirect to main page
	// getApplicationSettings().setPageExpiredErrorPage(getHomePage());

	// Intercept any unexpected error stacktrace and take to our page
	getRequestCycleListeners().add(new AbstractRequestCycleListener() {
		@Override
		public IRequestHandler onException(final RequestCycle cycle, final Exception e) {
			return new RenderPageRequestHandler(new PageProvider(new ErrorPage(e)));
		}
	});

	// Disable Wicket's loading of jQuery - we load Sakai's preferred version in BasePage.java
	getJavaScriptLibrarySettings().setJQueryReference(new PackageResourceReference(GradebookNgApplication.class, "empty.js"));

	// cleanup the HTML
	getMarkupSettings().setStripWicketTags(true);
	getMarkupSettings().setStripComments(true);
	getMarkupSettings().setCompressWhitespace(true);
}
 
Example #25
Source File: SiteStatsApplication.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
protected void init() {
	super.init();

	// Configure general wicket application settings
	getComponentInstantiationListeners().add(new SpringComponentInjector(this));
	getResourceSettings().setThrowExceptionOnMissingResource(false);
	getMarkupSettings().setStripWicketTags(true);
	getResourceSettings().getStringResourceLoaders().add(new SiteStatsStringResourceLoader());
	getResourceSettings().getResourceFinders().add(new WebApplicationPath(getServletContext(), "html"));
	getResourceSettings().setResourceStreamLocator(new SiteStatsResourceStreamLocator());
	getDebugSettings().setAjaxDebugModeEnabled(debug);

	// configure bottom page script loading
	setHeaderResponseDecorator(new JavaScriptToBucketResponseDecorator("bottom-script-container"));

	// Mount pages
	mountPage("/home", OverviewPage.class);
	mountPage("/reports", ReportsPage.class);
	mountPage("/useractivity", UserActivityPage.class);
	mountPage("/preferences", PreferencesPage.class);
	
	// On wicket session timeout, redirect to main page
	getApplicationSettings().setPageExpiredErrorPage(OverviewPage.class);
	getApplicationSettings().setAccessDeniedPage(OverviewPage.class);

	// Debugging
	debug = ServerConfigurationService.getBoolean("sitestats.debug", false);
	if(debug) {
		getDebugSettings().setComponentUseCheck(true);
		getDebugSettings().setAjaxDebugModeEnabled(true);
	    getDebugSettings().setLinePreciseReportingOnAddComponentEnabled(true);
	    getDebugSettings().setLinePreciseReportingOnNewComponentEnabled(true);
	    getDebugSettings().setOutputComponentPath(true);
	    getDebugSettings().setOutputMarkupContainerClassName(true);
		getDebugSettings().setDevelopmentUtilitiesEnabled(true);
	    getMarkupSettings().setStripWicketTags(false);
		getExceptionSettings().setUnexpectedExceptionDisplay(IExceptionSettings.SHOW_EXCEPTION_PAGE);
		// register standard debug contributors so that just setting the sitestats.debug property is enough to turn these on
		// otherwise, you have to turn wicket development mode on to get this populated due to the order methods are called
		DebugBar.registerContributor(VersionDebugContributor.DEBUG_BAR_CONTRIB, this);
		DebugBar.registerContributor(InspectorDebugPanel.DEBUG_BAR_CONTRIB, this);
		DebugBar.registerContributor(SessionSizeDebugPanel.DEBUG_BAR_CONTRIB, this);
		DebugBar.registerContributor(PageSizeDebugPanel.DEBUG_BAR_CONTRIB, this);
	}
	else
	{
		// Throw RuntimeDeceptions so they are caught by the Sakai ErrorReportHandler
		getRequestCycleListeners().add(new AbstractRequestCycleListener()
		{
			@Override
			public IRequestHandler onException(RequestCycle cycle, Exception ex)
			{
				if (ex instanceof RuntimeException)
				{
					throw (RuntimeException) ex;
				}
				return null;
			}
		});
	}

	// Encrypt URLs. This immediately sets up a session (note that things like CSS now becomes bound to the session)
	getSecuritySettings().setCryptFactory(new KeyInSessionSunJceCryptFactory()); // Different key per user
	final IRequestMapper cryptoMapper = new CryptoMapper(getRootRequestMapper(), this); 
	setRootRequestMapper(cryptoMapper);
}
 
Example #26
Source File: TransactionalRequestCycleListener.java    From pm-wicket-utils with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public IRequestHandler onException(RequestCycle cycle, Exception ex) {
	persistenceTransaction.setRollbackOnly();
	return null;
}
 
Example #27
Source File: SyncopeUIRequestCycleListener.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Override
public IRequestHandler onException(final RequestCycle cycle, final Exception e) {
    LOG.error("Exception found", e);

    PageParameters errorParameters = new PageParameters();

    IRequestablePage errorPage;
    if (instanceOf(e, UnauthorizedInstantiationException.class) != null) {
        errorParameters.add("errorMessage", BaseSession.Error.AUTHORIZATION.fallback());
        errorPage = getErrorPage(errorParameters);
    } else if (instanceOf(e, AccessControlException.class) != null) {
        if (StringUtils.containsIgnoreCase(instanceOf(e, AccessControlException.class).getMessage(), "expired")) {
            errorParameters.add("errorMessage", BaseSession.Error.SESSION_EXPIRED.fallback());
        } else {
            errorParameters.add("errorMessage", BaseSession.Error.AUTHORIZATION.fallback());
        }
        errorPage = getErrorPage(errorParameters);
    } else if (instanceOf(e, PageExpiredException.class) != null || !isSignedIn()) {
        errorParameters.add("errorMessage", BaseSession.Error.SESSION_EXPIRED.fallback());
        errorPage = getErrorPage(errorParameters);
    } else if (instanceOf(e, BadRequestException.class) != null
            || instanceOf(e, WebServiceException.class) != null
            || instanceOf(e, SyncopeClientException.class) != null) {

        errorParameters.add("errorMessage", BaseSession.Error.REST.fallback());
        errorPage = getErrorPage(errorParameters);
    } else {
        Throwable cause = instanceOf(e, ForbiddenException.class);
        if (cause == null) {
            // redirect to default Wicket error page
            errorPage = new ExceptionErrorPage(e, null);
        } else {
            errorParameters.add("errorMessage", cause.getMessage());
            errorPage = getErrorPage(errorParameters);
        }
    }

    if (errorPage instanceof BaseLogin) {
        try {
            invalidateSession();
        } catch (Throwable t) {
            // ignore
            LOG.debug("Unexpected error while forcing logout after error", t);
        }
    }

    return new RenderPageRequestHandler(new PageProvider(errorPage));
}
 
Example #28
Source File: TransactionRequestCycleListener.java    From wicket-orientdb with Apache License 2.0 4 votes vote down vote up
@Override
public IRequestHandler onException(RequestCycle cycle, Exception ex) {
	ODatabaseDocument db = ODatabaseRecordThreadLocal.instance().getIfDefined();
	if(db!=null && !db.isClosed()) db.rollback();
	return null;
}
 
Example #29
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);
	}
}
 
Example #30
Source File: ProfileApplication.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public IRequestHandler onException(final RequestCycle cycle, final Exception ex) {
	return null;
}