Java Code Examples for org.apache.wicket.request.cycle.RequestCycle#get()

The following examples show how to use org.apache.wicket.request.cycle.RequestCycle#get() . 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: ChartPanel.java    From inception with Apache License 2.0 7 votes vote down vote up
@Override
public void onRequest()
{
    RequestCycle requestCycle = RequestCycle.get();

    LearningCurve learningCurve = getModelObject();

    try {
        String json = addLearningCurve(learningCurve);

        // return the chart data back to the UI with the JSON. JSON define te learning
        // curves and the xaxis
        requestCycle.scheduleRequestHandlerAfterCurrent(
                new TextRequestHandler("application/json", "UTF-8", json));
    }
    catch (JsonProcessingException e) {
        LOG.error(e.toString(), e);
    }
}
 
Example 2
Source File: RecommendationServiceImpl.java    From inception with Apache License 2.0 6 votes vote down vote up
@EventListener
public void onAnnotation(AnnotationEvent aEvent)
{
    RequestCycle requestCycle = RequestCycle.get();
    
    if (requestCycle == null) {
        return;
    }
    
    Set<RecommendationStateKey> dirties = requestCycle.getMetaData(DIRTIES);
    if (dirties == null) {
        dirties = new HashSet<>();
        requestCycle.setMetaData(DIRTIES, dirties);
    }
    
    dirties.add(new RecommendationStateKey(aEvent.getUser(), aEvent.getProject()));
}
 
Example 3
Source File: WicketUtils.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Examples: https://www.projectforge.org/demo or https://www.acme.com/ProjectForge.
 * @return Absolute context path of the web application.
 */
public static String getAbsoluteContextPath()
{
  if (absoluteContextPath == null) {
    final RequestCycle requestCycle = RequestCycle.get();
    final String url = requestCycle.getUrlRenderer().renderFullUrl(Url.parse(requestCycle.urlFor(LoginPage.class, null).toString()));
    final String basePath = "/" + WICKET_APPLICATION_PATH;
    final int pos = url.indexOf(basePath);
    if (pos < 0) {
      log.warn("Couln't get base url of '" + url + "'. Sub string '" + basePath + "' expected.");
      return url;
    }
    absoluteContextPath = url.substring(0, pos);
  }
  return absoluteContextPath;
}
 
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: 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 6
Source File: OWebEnhancer.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
public OLoggerEvent enhance(OLoggerEvent event) {
	RequestCycle cycle = RequestCycle.get();

	if (cycle != null) {
		OrienteerWebSession session = OrienteerWebSession.get();
		if (session != null) {
			if (session.isClientInfoAvailable()) {
				WebClientInfo clientInfo = session.getClientInfo();
				event.setMetaData(OLoggerEventModel.PROP_REMOTE_ADDRESS, clientInfo.getProperties().getRemoteAddress());
				event.setMetaData(OLoggerEventModel.PROP_HOST_NAME, clientInfo.getProperties().getHostname());
			}
			if(session.isSignedIn()) {
				event.setMetaData(OLoggerEventModel.PROP_USERNAME, session.getEffectiveUser().getName());
			}
		}

		WebRequest request = (WebRequest)cycle.getRequest();
		event.setMetaData(OLoggerEventModel.PROP_CLIENT_URL, request.getClientUrl());
	}
	return event;
}
 
Example 7
Source File: AbstractAuthorizingRealm.java    From onedev with MIT License 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	Long userId = (Long) principals.getPrimaryPrincipal();						
	RequestCycle requestCycle = RequestCycle.get();
	if (requestCycle != null) {
		Map<Long, AuthorizationInfo> authorizationInfos = requestCycle.getMetaData(AUTHORIZATION_INFOS);
		if (authorizationInfos == null) {
			authorizationInfos = new HashMap<>();
			requestCycle.setMetaData(AUTHORIZATION_INFOS, authorizationInfos);
		}
		AuthorizationInfo authorizationInfo = authorizationInfos.get(userId);
		if (authorizationInfo == null) {
			authorizationInfo = newAuthorizationInfo(userId);
			authorizationInfos.put(userId, authorizationInfo);
		}
		return authorizationInfo;
	} else {
		return newAuthorizationInfo(userId);
	}
}
 
Example 8
Source File: MentionProcessor.java    From onedev with MIT License 5 votes vote down vote up
@Override
protected String toHtml(String userName) {
	if (RequestCycle.get() != null && OneDev.getInstance(UserManager.class).findByName(userName) != null) {
		return String.format("<a class='reference mention' data-reference='%s'>@%s</a>", 
				userName, userName);
	} else {
		return super.toHtml(userName);
	}
}
 
Example 9
Source File: AnnotatorStateImpl.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void fireViewStateChanged()
{
    RequestCycle requestCycle = RequestCycle.get();
    
    if (requestCycle == null) {
        return;
    }
    
    Optional<IPageRequestHandler> handler = requestCycle.find(IPageRequestHandler.class);
    if (handler.isPresent() && handler.get().isPageInstanceCreated()) {
        Page page = (Page) handler.get().getPage();
        page.send(page, BREADTH, new AnnotatorViewportChangedEvent(
                requestCycle.find(AjaxRequestTarget.class).orElse(null)));
    }
}
 
Example 10
Source File: Application.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public static String urlForPage(Class<? extends Page> clazz, PageParameters pp, String inBaseUrl) {
	RequestCycle rc = RequestCycle.get();
	String baseUrl = isUrlValid(inBaseUrl) ? inBaseUrl
			: (isUrlValid(getBaseUrl()) ? getBaseUrl() : "");
	if (!Strings.isEmpty(baseUrl) && !baseUrl.endsWith("/")) {
		baseUrl += "/";
	}
	return rc.getUrlRenderer().renderFullUrl(Url.parse(baseUrl + rc.mapUrlFor(clazz, pp)));
}
 
Example 11
Source File: DefaultIndexManager.java    From onedev with MIT License 5 votes vote down vote up
@Sessional
@Override
public void indexAsync(Project project, ObjectId commit) {
	int priority;
	if (RequestCycle.get() != null)
		priority = UI_INDEXING_PRIORITY;
	else
		priority = BACKEND_INDEXING_PRIORITY;
	IndexWork work = new IndexWork(priority, commit);
	batchWorkManager.submit(getBatchWorker(project.getId()), work);
}
 
Example 12
Source File: DefaultPullRequestManager.java    From onedev with MIT License 5 votes vote down vote up
@Sessional
@Override
public MergePreview previewMerge(PullRequest request) {
	if (!request.isNew()) {
		MergePreview lastMergePreview = request.getLastMergePreview();
		if (request.isOpen() && !request.isMergedIntoTarget()) {
			if (lastMergePreview == null || !lastMergePreview.isUpToDate(request)) {
				int priority = RequestCycle.get() != null?UI_PREVIEW_PRIORITY:BACKEND_PREVIEW_PRIORITY;			
				Long requestId = request.getId();
				transactionManager.runAfterCommit(new Runnable() {

					@Override
					public void run() {
						batchWorkManager.submit(getMergePreviewer(requestId), new Prioritized(priority));
					}
					
				});
				return null;
			} else {
				lastMergePreview.syncRef(request);
				return lastMergePreview;
			}
		} else {
			return lastMergePreview;
		}
	} else {
		return null;
	}
}
 
Example 13
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 14
Source File: WicketUtils.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Works for Wicket and non Wicket calling pages. For non Wicket callers the pageClass must be bookmarked in Wicket application.
 * @param pageClass
 * @param Optional list of params in tupel form: key, value, key, value...
 */
public static String getBookmarkablePageUrl(final Class< ? extends Page> pageClass, final String... params)
{
  final RequestCycle requestCylce = RequestCycle.get();
  if (requestCylce != null) {
    final PageParameters pageParameter = getPageParameters(params);
    return requestCylce.urlFor(pageClass, pageParameter).toString();
  } else {
    // RequestCycle.get().urlFor(pageClass, pageParameter).toString() can't be used for non wicket requests!
    final String alias = WicketApplication.getBookmarkableMountPath(pageClass);
    if (alias == null) {
      log.error("Given page class is not mounted. Please mount class in WicketApplication: " + pageClass);
      return getDefaultPageUrl();
    }
    if (params == null) {
      return WICKET_APPLICATION_PATH + alias;
    }
    final StringBuffer buf = new StringBuffer();
    buf.append(WICKET_APPLICATION_PATH).append(alias);
    try {
      for (int i = 0; i < params.length; i += 2) {
        if (i == 0) {
          buf.append("?");
        } else {
          buf.append("&");
        }
        buf.append(URLEncoder.encode(params[i], "UTF-8")).append("=");
        if (i + 1 < params.length) {
          buf.append(URLEncoder.encode(params[i + 1], "UTF-8"));
        }
      }
    } catch (final UnsupportedEncodingException ex) {
      log.error(ex.getMessage(), ex);
    }
    return buf.toString();
  }
}
 
Example 15
Source File: OLoggerEventMailDispatcher.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private String createLinkToEvent(OLoggerEventModel model) {
    RequestCycle cycle = RequestCycle.get();
    if (cycle != null) {
        PageParameters params = new PageParameters();
        params.add("rid", model.getDocument().getIdentity().toString().substring(1));
        CharSequence url = cycle.urlFor(ODocumentPage.class, params);
        return OLoggerModuleRepository.getModule().getDomain() + "/" + url;
    }
    return "";
}
 
Example 16
Source File: ServletWebResponse.java    From onedev with MIT License 5 votes vote down vote up
private UrlRenderer getUrlRenderer()
{
	RequestCycle requestCycle = RequestCycle.get();
	if (requestCycle == null)
	{
		return new UrlRenderer(webRequest);
	}
	return requestCycle.getUrlRenderer();
}
 
Example 17
Source File: WbWebSocketHelper.java    From openmeetings with Apache License 2.0 4 votes vote down vote up
private static CharSequence urlFor(final ResourceReference ref, PageParameters params) {
	RequestCycle rc = RequestCycle.get();
	ResourceReferenceRequestHandler handler = new ResourceReferenceRequestHandler(ref, params);
	return rc.getUrlRenderer().renderContextRelativeUrl(rc.mapUrlFor(handler).toString());
}
 
Example 18
Source File: RelationRenderer.java    From webanno with Apache License 2.0 4 votes vote down vote up
@Override
public void render(final CAS aCas, List<AnnotationFeature> aFeatures,
        VDocument aResponse, int aWindowBegin, int aWindowEnd)
{
    RelationAdapter typeAdapter = getTypeAdapter();
    Type type;
    Type spanType;
    try {
        type = getType(aCas, typeAdapter.getAnnotationTypeName());
        spanType = getType(aCas, typeAdapter.getAttachTypeName());
    }
    catch (IllegalArgumentException e) {
        // If the types are not defined, then we do not need to try and render them because the
        // CAS does not contain any instances of them
        return;
    }
    
    List<AnnotationFeature> visibleFeatures = aFeatures.stream()
            .filter(f -> f.isVisible() && f.isEnabled()).collect(Collectors.toList());
    
    Feature dependentFeature = type.getFeatureByBaseName(typeAdapter.getTargetFeatureName());
    Feature governorFeature = type.getFeatureByBaseName(typeAdapter.getSourceFeatureName());

    Feature arcSpanFeature = spanType.getFeatureByBaseName(typeAdapter.getAttachFeatureName());

    FeatureStructure dependentFs;
    FeatureStructure governorFs;

    Map<Integer, Set<Integer>> relationLinks = getRelationLinks(aCas, aWindowBegin, aWindowEnd,
            type, dependentFeature, governorFeature, arcSpanFeature);

    // if this is a governor for more than one dependent, avoid duplicate yield
    List<Integer> yieldDeps = new ArrayList<>();

    // Index mapping annotations to the corresponding rendered arcs
    Map<AnnotationFS, VArc> annoToArcIdx = new HashMap<>();
    
    for (AnnotationFS fs : selectCovered(aCas, type, aWindowBegin, aWindowEnd)) {
        if (typeAdapter.getAttachFeatureName() != null) {
            dependentFs = fs.getFeatureValue(dependentFeature).getFeatureValue(arcSpanFeature);
            governorFs = fs.getFeatureValue(governorFeature).getFeatureValue(arcSpanFeature);
        }
        else {
            dependentFs = fs.getFeatureValue(dependentFeature);
            governorFs = fs.getFeatureValue(governorFeature);
        }

        String bratTypeName = typeAdapter.getEncodedTypeName();
        Map<String, String> features = renderLabelFeatureValues(typeAdapter, fs,
                visibleFeatures);
        
        if (dependentFs == null || governorFs == null) {
            StringBuilder message = new StringBuilder();
            
            message.append("Relation [" + typeAdapter.getLayer().getName() + "] with id ["
                    + getAddr(fs) + "] has loose ends - cannot render.");
            if (typeAdapter.getAttachFeatureName() != null) {
                message.append("\nRelation [" + typeAdapter.getLayer().getName()
                        + "] attached to feature [" + typeAdapter.getAttachFeatureName() + "].");
            }
            message.append("\nDependent: " + dependentFs);
            message.append("\nGovernor: " + governorFs);
            
            RequestCycle requestCycle = RequestCycle.get();
            IPageRequestHandler handler = PageRequestHandlerTracker
                    .getLastHandler(requestCycle);
            Page page = (Page) handler.getPage();
            page.warn(message.toString());
            
            continue;
        }

        VArc arc = new VArc(typeAdapter.getLayer(), fs, bratTypeName, governorFs,
                dependentFs, features);
        arc.addLazyDetails(getLazyDetails(typeAdapter, fs, aFeatures));
        annoToArcIdx.put(fs, arc);

        aResponse.add(arc);

        // Render errors if required features are missing
        renderRequiredFeatureErrors(visibleFeatures, fs, aResponse);
        
        if (relationLinks.keySet().contains(getAddr(governorFs))
                && !yieldDeps.contains(getAddr(governorFs))) {
            yieldDeps.add(getAddr(governorFs));

            // sort the annotations (begin, end)
            List<Integer> sortedDepFs = new ArrayList<>(relationLinks.get(getAddr(governorFs)));
            sortedDepFs
                    .sort(comparingInt(arg0 -> selectAnnotationByAddr(aCas, arg0).getBegin()));

            String cm = getYieldMessage(aCas, sortedDepFs);
            aResponse.add(new VComment(governorFs, VCommentType.YIELD, cm));
        }
    }

    
    for (RelationLayerBehavior behavior : behaviors) {
        behavior.onRender(typeAdapter, aResponse, annoToArcIdx);
    }
}
 
Example 19
Source File: RecommendationServiceImpl.java    From inception with Apache License 2.0 4 votes vote down vote up
@EventListener
public void onAfterCasWritten(AfterCasWrittenEvent aEvent)
{
    RequestCycle requestCycle = RequestCycle.get();
    
    if (requestCycle == null) {
        return;
    }
    
    Set<RecommendationStateKey> committed = requestCycle.getMetaData(COMMITTED);
    if (committed == null) {
        committed = new HashSet<>();
        requestCycle.setMetaData(COMMITTED, committed);
    }

    committed.add(new RecommendationStateKey(aEvent.getDocument().getUser(),
            aEvent.getDocument().getProject()));        
    
    boolean containsTrainingTrigger = false;
    for (IRequestCycleListener listener : requestCycle.getListeners()) {
        if (listener instanceof TriggerTrainingTaskListener) {
            containsTrainingTrigger = true;
        }
    }
    
    if (!containsTrainingTrigger) {
        // Hack to figure out which annotations the user is viewing. This obviously works only 
        // if the user is viewing annotations through an AnnotationPageBase ... still not a 
        // bad guess
        IPageRequestHandler handler = PageRequestHandlerTracker
                .getLastHandler(requestCycle);
        Page page = (Page) handler.getPage();
        if (page instanceof AnnotationPageBase) {
            AnnotatorState state = ((AnnotationPageBase) page).getModelObject();
            requestCycle.getListeners()
                    .add(new TriggerTrainingTaskListener(state.getDocument()));
        }
        else {
            // Otherwise use the document from the event... mind that if there are multiple
            // events, we consider only the first one since after that the trigger listener
            // will be in the cycle and we do not add another one.
            // FIXME: This works as long as the user is working on a single document, but not if
            // the user is doing a bulk operation. If a bulk-operation is done, we get multiple
            // AfterCasWrittenEvent and we do not know which of them belongs to the document
            // which the user is currently viewing.
            requestCycle.getListeners()
                    .add(new TriggerTrainingTaskListener(aEvent.getDocument().getDocument()));
        }
    }
}
 
Example 20
Source File: AjaxWizard.java    From syncope with Apache License 2.0 4 votes vote down vote up
ApplyFuture(final AjaxRequestTarget target) {
    this.target = target;
    this.application = Application.get();
    this.requestCycle = RequestCycle.get();
    this.session = Session.exists() ? Session.get() : null;
}